Search code examples
javascriptsetinterval

Will setInterval drift?


This is a pretty simple question really. If I use setInterval(something, 1000), can I be completely sure that after, say, 31 days it will have triggered "something" exactly 60*60*24*31 times? Or is there any risk for so called drifting?


Solution

  • Here's a benchmark you can run in Firefox:

    var start = +new Date();
    var count = 0;
    setInterval(function () {
        console.log((new Date() - start) % 1000,
        ++count,
        Math.round((new Date() - start)/1000))
    }, 1000);
    

    First value should be as close to 0 or 1000 as possible (any other value shows how "off the spot" the timing of the trigger was.) Second value is number of times the code has been triggered, and third value is how many times the code should have been triggered. You'll note that if you hog down your CPU it can get quite off the spot, but it seems to correct itself. Try to run it for a longer period of time and see how it handles.