By Tomas Prado

2014-01-13 17:19:43 8 Comments

I got this code over here:

var date = new Date();
setTimeout(function(e) {
    var currentDate = new Date();
    if(currentDate - date >= 1000) {
         console.log(currentDate, date);
    else {
       console.log("It was less than a second!");
}, 1000);

In my computer, it always executes correctly, with 1000 in the console output. Interestedly in other computer, the same code, the timeout callback starts in less than a second and the difference of currentDate - date is between 980 and 998.

I know the existence of libraries that solve this inaccuracy (for example, Tock).

Basically, my question is: What are the reasons because setTimeout does not fire in the given delay? Could it be the computer that is too slow and the browser automatically tries to adapt to the slowness and fires the event before?

PS: Here is a screenshot of the code and the results executed in the Chrome JavaScript console:

Enter image description here


@MikeTeeVee 2019-05-23 21:18:23

I had a similar experience.
I was using something like this:

var iMillSecondsTillNextWholeSecond = (1000 - (new Date().getTime() % 1000));
setTimeout(function ()
    CountDownClock(ElementID, RelativeTime);
}, iMillSecondsTillNextWholeSecond);//Wait until the next whole second to start.

I noticed it would Skip a Second every couple Seconds, sometimes it would go for longer.
However, I'd still catch it Skipping after 10 or 20 Seconds and it just looked rickety.
I thought, "Maybe the Timeout is too slow or waiting for something else?".
Then I realized, "Maybe it's too fast, and the Timers the Browser is managing are off by a few Milliseconds?"

After adding +1 MilliSeconds to my Variable I only saw it skip once.
I ended up adding +50ms, just to be on the safe side.

var iMillSecondsTillNextWholeSecond = (1000 - (new Date().getTime() % 1000) + 50);

I know, it's a bit hacky, but my Timer is running smooth now. :)

@Mathletics 2014-01-13 17:29:00

Someone please correct me if I am misinterpreting this information:

According to a post from John Resig regarding the inaccuracy of performance tests across platforms (emphasis mine)

With the system times constantly being rounded down to the last queried time (each about 15 ms apart) the quality of performance results is seriously compromised.

So there is up to a 15 ms fudge on either end when comparing to the system time.

@EmptyArsenal 2014-01-13 17:32:07

That's one aspect of the problem. Another issue is the asynchronous nature of the browser, so depending on whatever else is in the queue, the timeout may be put on hold to deal with other jobs.

@Niels Keurentjes 2014-01-13 17:31:12

In general, computer programs are highly unreliable when trying to execute things with higher precision than 50 ms. The reason for this is that even on an octacore hyperthreaded processor the OS is usually juggling several hundreds of processes and threads, sometimes thousands or more. The OS makes all that multitasking work by scheduling all of them to get a slice of CPU time one after another, meaning they get 'a few milliseconds of time at most to do their thing'.

Implicity this means that if you set a timeout for 1000 ms, chances are far from small that the current browser process won't even be running at that point in time, so it's perfectly normal for the browser not to notice until 1005, 1010 or even 1050 milliseconds that it should be executing the given callback.

Usually this is not a problem, it happens, and it's rarely of utmost importance. If it is, all operating systems supply kernel level timers that are far more precise than 1 ms, and allow a developer to execute code at precisely the correct point in time. JavaScript however, as a heavily sandboxed environment, doesn't have access to kernel objects like that, and browsers refrain from using them since it could theoretically allow someone to attack the OS stability from inside a web page, by carefully constructing code that starves other threads by swamping it with a lot of dangerous timers.

As for why the test yields 980 I'm not sure - that would depend on exactly which browser you're using and which JavaScript engine. I can however fully understand if the browser just manually corrects a bit downwards for system load and/or speed, ensuring that "on average the delay is still about the correct time" - it would make a lot of sense from the sandboxing principle to just approximate the amount of time required without potentially burdening the rest of the system.

@Alexis Wilke 2015-12-16 09:10:16

Indeed, the problem is not specific to JavaScript. And an accurate of 50ms or less for a Browser executing an interpreted language, I think we're already pretty darn good.

@p.s.w.g 2014-01-13 17:31:39

It's not supposed to be particularly accurate. There are a number of factors limiting how soon the browser can execute the code; quoting from MDN:

In addition to "clamping", the timeout can also fire later when the page (or the OS/browser itself) is busy with other tasks.

In other words, the way that setTimeout is usually implemented, it is just meant to execute after a given delay, and once the browser's thread is free to execute it.

However, different browsers may implement it in different ways. Here are some tests I did:

var date = new Date();
setTimeout(function(e) {
    var currentDate = new Date();
}, 1000);

// Browser Test1 Test2 Test3 Test4
// Chrome    998  1014   998   998
// Firefox  1000  1001  1047  1000
// IE 11    1006  1013  1007  1005

Perhaps the < 1000 times from Chrome could be attributed to inaccuracy in the Date type, or perhaps it could be that Chrome uses a different strategy for deciding when to execute the code—maybe it's trying to fit it into the a nearest time slot, even if the timeout delay hasn't completed yet.

In short, you shouldn't use setTimeout if you expect reliable, consistent, millisecond-scale timing.

Related Questions

Sponsored Content

96 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6837157 View
  • 8413 Score
  • 96 Answer
  • Tags:   javascript arrays

28 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

61 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

37 Answered Questions

[SOLVED] What is the !! (not not) operator in JavaScript?

  • 2009-04-24 08:13:58
  • Hexagon Theory
  • 560072 View
  • 3146 Score
  • 37 Answer
  • Tags:   javascript operators

86 Answered Questions

[SOLVED] How do JavaScript closures work?

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

3 Answered Questions

40 Answered Questions

[SOLVED] For-each over an array in JavaScript

67 Answered Questions

[SOLVED] What is the most efficient way to deep clone an object in JavaScript?

Sponsored Content