Date.now() returned a time 11 seconds off. How?

Viewed 58

Platform: Windows 10 Home, node.js 10.20.1

This actually just happened. When subtracting the current time from a previous time, I got a negative number.

checking for the thing... 0s
checking for the thing... -8s
checking for the thing... -5s
checking for the thing... -2s
checking for the thing... 1s
checking for the thing... 4s

Simplified code:

const util = require('util');
const sleep = util.promisify(setTimeout);

const doIt = async() => {
    const started = new Date();
    let tries = 100;
    let isFound = false;
    while (!isFound && tries--) {
        try {
            const elapsedSeconds = Math.round(((new Date()) - started) / 1000);
            console.log(`checking for the thing: ${elapsedSeconds}s`);
            /* something throws an error if it fails */
            isFound = true;
        } catch (e) {
            await sleep(3000);
        }
    }
};

doIt();

As you might expect, a typical run of this code looks like this.

checking for the thing... 0s
checking for the thing... 3s
checking for the thing... 6s
checking for the thing... 9s
checking for the thing... 12s
checking for the thing... 15s

I haven't been able to replicate the issue, so far.

Presumably the inaccurate new Date() was the start time, since the iterations stayed at the correct offset relative to each other.

So how did this occur?

I know that checking the wallclock time is not always accurate, but I didn't expect it to be 11 seconds off.

I speculated that NTP might be the culprit, since it could alter system time. NTP is turned on, and the system is synced to time.windows.com. But if it were NTP's fault somehow, isn't it supposed to apply corrections gradually?

0 Answers
Related