can setInterval drift over time?

setinterval timer
javascript keeping time
accurate interval js
nodejs accurate timer
js start timer
javascript date accuracy
javascript accurate setinterval

I have 2 node.js webservers. I cache data inside webservers. I sync the cache load/clear based on system time. I have done time sync of all my hosts.

Now I clear cache every 15 mins using following code:

millisTillNexthour = "Calculate millis remaining until next hour"

setTimeout(function() {
  setInterval(function() {
    cache.clear();
  }, 60000*15);
}, millisTillNexthour);

My expectation is even if this process runs for ever, cache will be cleared every 15th minute of each hour of the day.

My question is: can setInterval drift over time?

For eg: right now it clears cache at 10:00 10:15 10:30 10:45 11:00 ......

Can it happen that instead of 10:15 system time, setInterval gets executed at 10:20 system time when it was supposed to clear cache at 10:15??

I am not sure how this works. Please shed some light. I hope I explained my question well.


setInterval is definitely drifting (although I agree that it should not be). I'm running a Node.js server with an interval of 30 seconds. On each tick, a few async web requests are made which from beginning to end take roughly 1 second. No other user-level/application processing happens in the intervening 29 seconds.

However, I notice from my server logs that over the course of 30 minutes, a drift of 100ms occurs. Of course, the underlying operating system is not to blame for the drift and it can only be some defect of Node.js's design or implementation.

Will setInterval drift?, x and 10x (while 10x being more proper). However setInterval still appears to be slipping over time. output from the above code: STEP: 1, Drift: 1  This shows a drift of 12ms over the 30 second testing period. In production i am using setInterval with 60 000ms delay, but since the system tends to have very large uptime, slippage from the starting point is starting to become an issue. lpinca added the timers label on Jul 15, 2018. This comment has been minimized.


I am very disappointed to notice that there is a bug in the NodeJS implementation of setInterval. Please take a look at here:

https://github.com/nodejs/node/issues/7346#issuecomment-300432730

setInterval keeps drifting over time · Issue #21822 · nodejs/node , Issue with setInterval function losing accuracy over time. setInterval does drift because each iteration will be a few milliseconds late, and that gets passed on to​  setInterval does drift because each iteration will be a few milliseconds late, and that gets passed on to future iterations, so if each iteration is 3ms late (which would be normal) by the 5th, you will be 15 milliseconds behind.


You can use Date() object to set specific time and then add a certain number of milliseconds to the date.

Issue with setInterval function losing accuracy over time., Clock synchronization is very important in wireless sensor networks [12–18, 20 need to resynchronize their clocks every so often due to their local clock drift. It is also possible not to synchronize all of the nodes in the network at a set interval. So no drift issue there. In terms of making a more precise setInterval(), I can imagine it: take the current time, compare it to the time the interval expects it to be, then adjust the next interval to compensate. What I'm not as sure about is whether it really makes sense to put into moment itself, as opposed to a plugin.


It definitly can because of how Javascript works (See Event Loop)

Javascript event loop executes the setInterval queue when other queued events are finished. These events will take some time and it will effect your setInterval function's execute time and it will eventually drift away as time passes.

Underwater Acoustic Sensor Networks, In certain contexts, as when a browser tab or window loses focus, setInterval and setTimeout timing can drift, diminishing their accuracy. setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval. These methods are not a part of JavaScript specification. But most environments have the internal scheduler and provide these methods.


I'm probably more than a bit late to the party here, but this is how I solved this particular time-slipping problem just now, using a recursively called setTimeout() function instead of using setInterval().

var interval = 5000;
var adjustedInterval = interval;
var expectedCycleTime = 0;

function runAtInterval(){
    // get timestamp at very start of function call
    var now = Date.now();

    // log with time to show interval
    console.log(new Date().toISOString().replace(/T/, ' ').replace(/Z/, '') + " runAtInterval()");

    // set next expectedCycleTime and adjustedInterval
    if (expectedCycleTime == 0){
        expectedCycleTime = now + interval;
    }
    else {
        adjustedInterval = interval - (now - expectedCycleTime);
        expectedCycleTime += interval;
    }

    // function calls itself after delay of adjustedInterval
    setTimeout(function () {
        runAtInterval();
    }, adjustedInterval);
}

On each iteration, the function checks the actual execution time against the previously calculated expected time, and then deducts the difference from 'interval' to produce 'adjustedInterval'. This difference may be positive or negative, and the results show that actual execution times tend to oscillate around the 'true' value +/- ~5ms.

Either way, if you've got a task that is executing once a minute, and you run it for an entire day, using this function you can expect that - for the entire day - every single hour will have had 60 iterations happen. You won't have that occasional hour where you only got 59 results because eventually an entire minute had slipped.

More Accurate JavaScript Timers with Web Workers, Timers allow you to execute code at a set time or repeatedly using an interval. This is accomplished with the setTimeout, setInterval, and clearInterval functions. https://stackoverflow.com/questions/985670/will-setinterval-drift. Another thing to talk about here with setInterval is setting a loop counter and clearing the interval when that loop count is hit. var counter = 0 intervalId = 0; function myLoopFunction() { intervalId = setInterval(function() { //make this is the first thing you do in the set interval function counter++; //do you code for setInterval() and clearInterval under normal conditions here


Explain the working of timers in JavaScript? Also elucidate, This is my code: var seconds = 0; setInterval(function() { timer. and they do not keep a constant pace but tend to drift (as you have observed). 1000)); // in seconds // alternatively just show wall clock time: output(new Date(). Display the current time (the setInterval () method will execute the function once every 1 second, just like a digital watch): var myVar = setInterval (myTimer, 1000); function myTimer () {. var d = new Date (); var t = d.toLocaleTimeString(); document.getElementById("demo").innerHTML = t; }


Brain Injury Medicine: Principles and Practice, In this schedule, reinforcement happens after a set interval of time. This schedule can cause a ''scallop'' effect in which appropriate behavior increases as the time for Application of reinforcement may drift from treatment plan design. Do you see the same drift in Safari/node using setInterval? If you need more accurate timing, it's possible to attempt that now using a combination of Time.now and Process.sleep (every time you get a message, check the timestamp and calculate how long you want to sleep for).


Will setInterval drift?, 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? countdown​() and loop with setInterval but its drifting 1-3 milliseconds per  My test is to execute setInterval with a 100ms interval. The callback spends about 5-7ms calculating fibonacci. At the start of the callback I record the current time. I let the setInterval run for 10 seconds. Afterwards I calculate the delta between setInterval calls. The aforementioned browsers have an average delta between 100-103ms.