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

Using Webpack to directly embed image paths in your code

I am working on a project that uses webpack and vue.js. I encountered an issue when trying to add an image to the vue template using src '/images/imageName.png', which resulted in a 404 error. How can I adjust the configuration to recognize absol ...

Tips for replacing all occurrences of a specific string in HTML while preserving JavaScript attributes

Is there a way to use RegEx to replace part of an HTML document without affecting the root element or other elements like event listeners? Consider this scenario: for (; document.body.innerHTML.indexOf(/ea/) != -1;) { document.body.innerHTML = docu ...

What is the best way to modify a variable's value from a nested controller and vice versa?

There seems to be an issue with changing the 'mensaje' variable in both the "padre controller" and the "hijo controller" and visualizing the changes. When clicking on "cambiar padre," the value changes as expected. However, if I then click on "ca ...

Change the syntax to use async-await

Is it worth converting the syntax to async-await and how can I achieve this? // ---- UserRoutes ---- router.get('/user', middlewareJwt.jwtHandler, function (req, res) { UserService.get(req.userId, (user) => successCbk(res, 200, { ...

"Executing the ajax send() function does not result in any changes to the

Just starting to explore ajax and I need some help. Can anyone explain why the address bar is not updating when using ajax send()? The connection is working, but it keeps displaying "There is no variable!" PS: Please note that I prefer not to use JQuery. ...

Utilizing a function argument within the :not() selector

I am currently working towards the objective of selecting all elements in my document except for those within a specific class. This is what I have come up with so far: var x = document.querySelectorAll(":not(.myParameter)"); My aim is to make 'myPa ...

What could be causing these strange white lines to show up on my AFrame meshes?

When I import a GLB scene with baked textures into A-Frame using THREE.js, I am experiencing an issue where white lines appear on my objects (pictured below). The walls are grouped meshes which may explain the lines appearing there, but I am puzzled as to ...

Sorting items in backbone.js can be achieved by using the sortBy method

Currently, I am delving into learning backbone.js and have decided to create my own Todo application using backbone.js along with a local storage plugin. At this point, I have successfully developed the Todo app where you can add and remove tasks. However, ...

What is the best way to link options from a select directive with a different array?

Update: the working jsfiddle can be found here: http://jsfiddle.net/robertyoung/jwTU2/9/ I'm in the process of developing a webpage/app using AngularJS. The specific functionality I aim to achieve involves allowing users to add a row to the timecard ...

using a ternary operator within the map function

Currently, I'm developing a web application that allows users to view a list of items and mark certain items as favorites. The favorites are stored in an array of IDs assigned to a prop (this.props.favorites). To ensure there are no duplicate entries, ...

MANDATORY activation of CONFIRMATION

Hello everyone, I'm seeking assistance with my code. Below is the form code I need help with: <form action="input.php" method="POST"> <input type="text" class="input" name="firstname" placeholder="First Name" required> <input t ...

Troubleshooting ASP.NET Content Page Error: jQuery Object Expected

Currently working on designing a personal ASP.NET Web page, I have encountered an issue with making a sticky div using jQuery. Despite all my other jQuery functions functioning properly, the sticky div seems to be causing trouble. stickydiv.js $(document ...

Extracting data from web pages using JavaScript and PHP

Using the following script, I am able to scrape all the items from this specific page: $html = file_get_contents($list_url); $doc = new DOMDocument(); libxml_use_internal_errors(TRUE); if(!empty($html)) { $doc->loadHTML($html); ...

Incorporating User Input: Adding Paragraph Elements with HTML and Javascript to a Div Container

I am attempting to test my ability by creating a basic webpage. My goal is to take the text entered by the user in a textarea and add it to the page using a button. This button should generate a new paragraph element, place the user input inside of it, and ...

Updating or removing fullCalendar events in Symfony

I'm struggling to figure out how to update or delete fullcalendar events in my Symfony project. When adding a new event, I open a modal window with a form for submitting the event and inserting it into the database. This is my working controller: $ ...

Icon button not found

I have created a reusable hook component for input fields. The TextField renders perfectly, but the IconButton is not showing up. const InputHookComponent = (props) =>{ const [val, setval]=useState(""); const cmp = <TextField type={ ...

What is the best way to make a box modal function that displays a different image source than the one shown in the modal?

I'm looking to create a box modal that shows one image on the page, and then displays a different image in the popup when clicked. Here's what I currently have: <div class="row"> <div class="modal-image"><img id="myImg" src="http ...

Emphasize the close button within the popup window as soon as it appears

One of my coding challenges involves a div element, shown below: <div id="modal" tabindex="-1" ng-show="booleanvariable"></div> When the value of ng-show is true, this div is displayed. A "close" button located under the div should be focused ...

Issues encountered while sending HTML Form data to MySQL with Node JS

I have been experimenting with a basic html form to mysql using nodejs, but unfortunately it is not functioning as expected. The HTML file is named index.html and the Node.js file is called test.js. Below you can find my code: My HTML <!DOCTYPE html&g ...

Verify the presence of an image

I have a code snippet that I use to refresh an image in the browser. However, I want to enhance this code so that it first checks if the image exists before displaying it. If the image does not exist, I want to display the previous version of the picture i ...