Synchronizing Events across Two JavaScript Applications

In my game app (using Electron) and web app (testing on Android Chrome), they communicate through a websocket server to coordinate a countdown. I've noticed that in environments with low latency, the synchronization is fine. However, when there is more lag in the system, the Electron app seems to start the countdown far earlier than the web app. Despite checking all calculations, the synchronization just doesn't work as expected.

Initially, the web app triggers the countdown by sending a starting time to the game app

const timeToGameStart:number = peerConnection.timeToGameStart(); // time to game start = 3 x (the longest time it took to pass a previous msg from game app to web app) 
const currUnixTime:number = peerConnection.currUnixTime();
const startGameTime:number = currUnixTime + timeToGameStart;
const startGame:StartGame = <StartGame>{
    msg_data_type:Msg_Data_Type.StartGame,
    game_start_time:startGameTime
}
peerConnection.passMsg(startGame);
setTimeout(timer.start, timeToGameStart);

Below is the part of the code in the app that handles the message passed to the server

const gameStartTime:number = (<StartGame> msgData).game_start_time;
const currUnixTime:number = ServerConnection.currUnixTime();

// If we are on time, wait until the right time, else if we are late, start at the next increment 3,2,1
const countDownLength:number = 3;
if (currUnixTime <= gameStartTime) {
    setTimeout(()=>startCountDown(countDownLength), currUnixTime - gameStartTime);
} else {
    const timeWeAreLateBy:number = currUnixTime - gameStartTime;
    const timeWeAreLateByInSec:number = Math.ceil(timeWeAreLateBy / 1000);
    const shortCountDownLen:number = Math.max(countDownLength - timeWeAreLateByInSec, 0);
    const timeToNextSec:number = Math.max((1000 * timeWeAreLateByInSec) - timeWeAreLateBy, 0);

    setTimeout(()=>startCountDown(shortCountDownLen), timeToNextSec);
}

Answer №1

The issue arises from the fact that these two distinct processes are running on different operating systems, each with its own interpretation of time. Consequently, (new Date()).getTime() yields dissimilar results, with a 2-second disparity. This discrepancy misled the controller into believing there was no delay in the connection and prompted it to instruct the app to commence immediately.

To address this challenge, I implemented a method to establish a consistent time reference. Upon connecting to the server, each app synchronizes its time by requesting the server's current timestamp.

I opted for a straightforward algorithm to achieve time synchronization without requiring pinpoint precision. The algorithm involved calculating the deviation between the process timing and the server's time using the formula

server_time_diff = server_time - (received_time - RTT/2)
. To determine the unified or server time, one could simply invoke new Date() + server_time_diff, where RTT denotes the time spent fetching the server timestamp.

I am open to any suggestions for enhancing my algorithm.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Difficulty encountered when creating step definitions - Implementing Cucumber and Appium using JavaScript

I am currently embarking on a project that serves as more of a proof of concept. For me, this is a POC since I am aware that similar projects have been executed before. My focus revolves around working with Cucumber.js, Appium Server/Client, Node, and Jav ...

What is the best way to prevent clicking and scrolling on a webpage?

I have added a "more" button to the bottom left of my website to reveal a menu. Upon clicking the button, the plus sign changes to an x. I would like the page to disable click and scroll actions when the plus sign is clicked. <div class="dropup"> ...

Unable to assign value to a public variable in Angular

I am facing an issue where I am trying to retrieve a value from the localStorage and assign it to a variable. However, when I try to use that variable in functions, it is coming up as undefined. code export class DashboardService { public token: any; ...

"Utilizing Bootstrap's hamburger menu for a sleek solution when your menu becomes overcrowded

One interesting aspect of Bootstrap is its ability to collapse menu items into a hamburger menu within the navbar at specific window size breakpoints. However, there are instances where even on larger screens that exceed these breakpoints, the hamburger bu ...

Issues with Rxjs pipe and Angular's Http.get() functionality are causing complications

Working with an Angular 4 Component that interacts with a Service to fetch data is a common scenario. Once the data is retrieved, it often needs to be transformed and filtered before being utilized. The prevailing method for this task is through the use of ...

Numerous identifiers and a distinct title

As a beginner in Ruby and JavaScript, I am unsure of my actions. I have a dropdown box that I want to display by unique name. Using JavaScript (CoffeeScript), I retrieve results with JSON. I have implemented a method to display by unique name, which is f ...

"Combining the power of React and Rails with REST API and the ActionC

I have a React frontend (not using the react-rails gem) and I want to utilize Rails API for real-time interaction. Currently, I have this functioning post.coffee code in my Rails application for ActionCable: App.post = App.cable.subscriptions.create("Post ...

Locating the value of field in an array of JSON data

let data = [{ a: 1, b: 2}, { a: 11, b: 12}, { a: 31, b: 23}, { a: 51, b: 24}] How can you retrieve the object where a = 11 ? For simple arrays, one could use x.indexOf('1');. So a potential solution could be: let result = data.find(obj => o ...

What is the best way to present CouchDB design documents in a clear and reader-friendly format?

Struggling to define views in a readable way because they are set in JSON in CouchDB. Consider this example: { "language": "javascript", "views": { "by_location": { "map": "function(doc) { if (doc.location != null) emit(doc.l ...

Why does this particular check continue to generate an error, despite my prior validation to confirm its undefined status?

After making an AJAX call, I passed a collection of JSON objects. Among the datasets I received, some include the field C while others do not. Whenever I try to execute the following code snippet, it causes the system to crash. I attempted using both und ...

Ways to calculate the memory utilization of a JavaScript object

Suppose I want to compare the efficiency of storing bits of a static canvas/image with Alpha more or less than 0.5 using an "array of array of number" versus an "array of string," which would be better in terms of memory usage and speed? var c = $('m ...

Angular 2, React, or any other modern framework.getList()?.map

I have experience working on multiple angular 1 projects and I absolutely enjoyed it. We have several upcoming projects where I need to recommend JavaScript frontend libraries/frameworks. With the decline of angular 1 and mixed reviews about angular 2&apos ...

Fixing a scrolling element within a div located below the screen is my goal, ensuring it remains fixed in place as the user scrolls

I'm facing a challenge that I need help with: My HTML/CSS layout currently looks like this: Screenshot of how my CSS/HTML appears on the screen upon page load: As I scroll down, I encounter a green element: While scrolling down -> Upon further s ...

The @angular/fire package is unable to locate the AngularFireModule and AngularFireDatabaseModule modules

I am facing some challenges while trying to integrate Firebase Realtime Database into my Angular project. Specifically, I am encountering difficulties at the initial step of importing AngularFireModule and AngularFireDatabaseModule. To be more specific, I ...

Utilizing PHP with WordPress: Execute the specified .js file if the link includes the ID "124"

I am currently using WordPress on my local server and I want to set up a redirect after a user submits the contact form through the Contact Form 7 Plugin. I am looking to redirect them to a specific page, but so far, the plugins I have tried have caused th ...

Creating an interactive API endpoint in AngularJS for a DreamFactory stored procedure just got easier with these simple steps

If I am using a factory/service to access my API in DreamFactory. FoundationApp.factory('testAPI', function($resource, ChildID) { return $resource('http://Domain.com/rest/RemoteDB/_proc/TimeLog_Checkin(:ChildID)/?app_name=App&fields ...

What are the reasons for the POST method malfunctioning in a mobile web application?

Currently, I am in the process of developing a mobile web application using PhoneGap. At the moment, I am successfully passing data between the client (HTML page on the mobile device) and the server (PHP on the server) using the GET method. However, when a ...

The return value of fs.mkdirSync is undefined

I'm facing a challenge with creating a directory and utilizing that directory as a variable to extract files from zip/rar files. The section of code that is causing an error is shown below: var fileZip = fileName.replace(/^.*[\\\/]/, ...

Control the transparency of the initial parent div that includes an *ngFor loop

I want to add opacity only to the first div which contains an icon and a heading in another nested div. The second div should remain fully visible (opacity: 1). Here is the HTML structure: <div class="row clearfix"> <div class="col-lg-3 col- ...

What is the optimal method for assigning a value to a specific key within a JavaScript JSON object?

Below is the information stored in a file called "fokontanys.json": { "vzdveg643": { "lldistrict":"Ambilobe", "id_province": 7, "id": null }, "vzvsdv5327": { "lldistrict ...