Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
What happens in node.js when you start a setInterval(), but do some synchronous work? setInterval() calls get dropped.
sync task start
sync task done
setInterval(function() {
var now = new Date();
}, 100);
setTimeout(function() {
var start = new Date();
var now = new Date();
console.log('sync task start');
while (now.getTime() - start.getTime() < 1000) {
now = new Date();
console.log('sync task done');
}, 500)

davisjam commented Nov 8, 2016

I don't think "dropped" is really the right turn of phrase here. setInterval CBs get run at a particular point in the event loop (during timer handling way down in libuv). If the event loop is blocked due to synchronous work, the setInterval CBs will be delayed until the work is finished.

The relevant information from the Node.js docs can be found in setTimeout:

The callback will likely not be invoked in precisely delay milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire, nor of their ordering.
The callback will be called as close as possible to the time specified.

In your example, each setInterval CB is invoked as close to 100ms after the previous one as possible. It just so happens that the synchronous work means that "1 second" later" is the best Node.js can do.


scottnonnenberg commented Jan 13, 2017

It's fair to argue from the documentation, but it's also fair to argue from user expectation. setInterval(fn, 100) is often expected to mean 'run this 10 times per second.' Thus, an interruption in the event loop of 1 second breaks that expectation - expected calls are dropped completely.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment