Last active
September 7, 2018 22:42
-
-
Save scottnonnenberg/56597f27c6cd44dfbfee to your computer and use it in GitHub Desktop.
What happens in node.js when you start a setInterval(), but do some synchronous work? setInterval() calls get dropped.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2015-03-23T19:41:49.232Z | |
2015-03-23T19:41:49.367Z | |
2015-03-23T19:41:49.470Z | |
2015-03-23T19:41:49.571Z | |
sync task start | |
sync task done | |
2015-03-23T19:41:50.632Z | |
2015-03-23T19:41:50.733Z | |
2015-03-23T19:41:50.834Z | |
^C |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
setInterval(function() { | |
var now = new Date(); | |
console.log(now.toJSON()); | |
}, 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) |
Why would callbacks being called out of order? I assumed it was a single thread model, so the callbacks should be executed off one stack.
If callbacks can be called out of order, that would make shared state more difficult to manage.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @scottnonnenberg,
Thanks for the snippet — really useful when explaining some of the Node.js aspects!
I agree with @davisjam, "dropped" isn't the right word here. It becomes more clear with the following patch:
which will result in the following output:
Rephrasing official documentation
we should read that as "the callback will be called not earlier than the specified interval".
Everything runs in parallel except for our code ;)
Best,
Max