What is the best approach to comparing two times in JavaScript to ensure accuracy after an NTP time update?

We are facing an issue with a JavaScript function that retrieves the start and end times of two events:

var startTime = new Date().getTime();
// A lengthy task is executed
var endTime = new Date().getTime();

The problem we encountered is that getTime() seems to rely on the system clock. Unfortunately, there have been instances where the user's clock changed between these two calls, possibly due to a Windows NTP time update (in which Windows fetches the accurate time from a server and adjusts the system clock). This results in a scenario like this:

startTime = 12:00:00
// Task starts for 30 seconds
// NTP time update detects a one-minute difference and corrects the clock
endTime = 11:59:30 // End time before start time

Is there a solution to comparing two times that can withstand an NTP time update? Our JavaScript application cannot access servers outside our corporate network, ruling out the option of querying an NTP server directly.

Answer №1

Similar to the cleaning lady analogy, I don't handle windows. My expertise lies in various ntp daemons on unix-like machines accumulated over the years.

ntpd is designed not for making drastic time adjustments but rather for fine-tuning the system clock's speed. If a significant step is needed, it indicates that your machine's initial time was way off or there's a clock issue (or possibly poor hardware).

In normal circumstances, ntpd ensures a continuous and smooth timescale without major disruptions (although there may be slight variations). Only when the gap between system time and UTC is excessively large does a "step" occur, potentially causing time to reverse, with notifications typically being logged if this happens.

System time steps can lead to other complications as well, such as confusing make commands.

Modern ntpd provides options to adjust the threshold at which a step is triggered.

Possible solutions:

You could monitor where your systems log NTP step occurrences and respond accordingly (though this may be challenging across different platforms).

Rather than relying solely on system time, consider using an alternate time measurement method.

If accessing a public NTP server directly isn't feasible, retrieve time information from a server with a reliable clock via http(s) instead. While not as precise as NTP, if you're dealing with differences of around 30 seconds, the impact of using http(s) might be minimal.

If high accuracy is crucial, tunnel NTP through http(s) to a webserver and let NTP manage the transmission delay. It involves additional effort, but could be a solution in urgent cases.

For environments within a corporate setting, setting up internal NTP servers is relatively straightforward. Alternatively, ready-made timeservers are available for purchase (e.g., Meinberg) and network time can be broadcasted using NTP within the local network.

However, I do have reservations about the necessity of accurately measuring time elapsed within an application.

Further details can be found here:

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

Finding a potential data breach in Node.js, MongoDB, and Chrome, exposed passwords are

My web app is built using nodejs with mongodb as the database backend, and I am encountering an issue with Chrome browser flagging my login process via passport.js as an exposed password. How can I prevent this warning? Should I implement something like Bc ...

What is the most efficient way to transfer form data from one JSP page to another?

I need to transfer information from one webpage (1.jsp) to another webpage (2.jsp). The data that needs to be transferred includes checkboxes, radio buttons, and drop downs. This data will be used in 2.jsp to generate the appropriate page. Is there a way ...

The "self" variable in the Node.js prototype object fails to retain the correct context for the callback function

Although I have experience as a developer, I am new to Java Script and Node.js. I have searched through various examples and Stack Overflow answers, but I couldn't find a simple and complete example of a prototypical class with correct 'self&apos ...

Changing a callback function into a promise in Node.js for OpenTok integration

MY FUNCTIONAL CODE (SUCCESSFULLY WORKING!) I have developed a function with callback to generate tokens and create sessions for OpenTok. This function is then exported to the application. The function //Dependencies var opentok = require('./ot&ap ...

Ways to utilize a string as an object?

Hey there! I'm just getting started with software development and currently working on an application using React Native. The backend is sending me a large data set, but here's a snippet of it. My challenge is that I want to access the first ele ...

Having trouble getting autocomplete to work with JQuery UI?

Currently facing issues in implementing the Amazon and Wikipedia Autocomplete API. It seems that a different autocomplete service needs to be used based on the search parameter. Unfortunately, neither of the services work when adding "?search=5" for Wikipe ...

Mastering the Art of Resizing Video Controls: A

https://i.stack.imgur.com/jTgap.png https://i.stack.imgur.com/Exf6Y.png On the initial screenshot, the video player displays normal controls. However, on the same website with identical CSS, the second video player shows different control settings. // C ...

Respond to a recommendation with a response

I've been working on setting up a bot for my Discord server, and I recently added a "marry" command to it. Whenever a user makes an offer, a message announcing the proposal pops up with two reaction options. The first reaction signifies yes, while th ...

Modify one specific variable within my comprehensive collection on Firebase Firestore

After clicking the button, I need to update a variable. The variable in question is "bagAmount" and it is stored in my firestore collection. Here is a link to view the Firestore Collection: Firestore Collection Currently, I am able to update one of the va ...

Processing made easy with jQuery

In my HTML page, I have multiple rows that represent records from a database. Each row contains input fields and a link at the end. When I click on the link, I need to capture the values of the input fields within the same row. Here is an example of the H ...

Focus on selecting each label within a table using JavaScript

In my current setup, I am attempting to customize radio buttons and checkboxes. Array.from(document.querySelectorAll("tr")).forEach((tr,index)=>{ var mark=document.createElement("span"); Array.from(tr.querySelectorAll("input")).forEach((inp,index ...

Create a visual representation of an item within a framework using an Angular directive

I am interested in using a directive to draw a triangle above a series of div elements. In my scenario, I have four squares and two values: charge and normal. The value of charge determines the color of the squares, while normal is used for drawing the t ...

Verify the ability to view a webpage

I am currently working on creating a method to check if data access is equal to next.data.access. Since it's an array, I cannot use the includes method. It would be enough for just one of the data access values in the array to return true. auth.guard ...

Dealing with Unreliable Data in Scatter Plots using React and HighCharts

Initially, I utilized line charts for my data visualization needs. However, I now require multiple data points on the same X-Axis with tooltips, which has led me to discover HighCharts behavior: "In a line chart, by default, Highcharts will display t ...

What is the best way to efficiently load all of my web applications within the web application that I am currently developing?

https://i.stack.imgur.com/IAjIW.png Greetings! I am currently a novice Web Developer and here is my current situation: I am working on developing 3 web applications, with one additional application that will load all three of them. Please refer to the im ...

A blank page is appearing mysteriously, free of any errors

I have experience with ReactJs, but I am new to Redux. Currently, I am working on implementing an async action where I call an API and display the data received from it. Initially, when all the Redux components (actions, reducers, containers) were on a sin ...

Exploring ES6: Harnessing the Power of Classes

I am currently learning the ES6 syntax for classes. My background is in C#, so I apologize if my terminology is not accurate or if something seems off. For practice, I am working on building a web app using Node and Express. I have defined some routes as ...

The async waterfall is encountering a Typeerror due to the nextcallback function not being defined properly

async.waterfall([1,2,3,4].map(function (arrayItem) { return function (lastItemResult, nextCallback) { // performing the same operation for each item in the array var itemResult = (arrayItem+lastItemResult); // pa ...

Implementing a secure route in React that asynchronously checks user authentication status

Currently, I have a React app utilizing Auth from the aws-amplify package (version 5.3.8) and react-router-dom (version 5.3.0). Although there is a version specifically for React available, it necessitates using at least version 5.0.0 of react-scripts, whe ...

Vue js for filtering and replacing prohibited words

For this scenario, our objective is to screen the words in our input: <input type="text" class="form-control" placeholder="Write something..." v-model="todoInput""> Below are the restricted words that we aim to substitute in the input "restrict ...