Timer events in node.js are not guaranteed to be called at an accurate time.
If I call setTimeOut() for say, 10 seconds from now, then execute a
set of long running commands, does Node.js/JavaScript wait until those
commands finish executing the function set up in setTimeOut?
Yes, it waits until the current code executing in node.js is done before it can serve the next timer event.
Is the same true with setInterval()?
Yes, same mechanism for setInterval()
.
Here's some explanation of how the node.js system works.
node.js is a single threaded event-driven system (technically threads are used inside of node.js, but it only runs one single thread of your JS code).
When you use setTimeout()
or setInterval()
some internal mechanism inside of node.js uses system timers to know when the next timer should fire. At that moment, an event is inserted into the node.js event queue. If node.js is doing nothing at that moment, then the event is triggered immediately and the appropriate callback function is called immediately.
But, if node.js is busy running code and if other events are in front of the timer event in the event queue, then the timer event will not be triggered immediately.
Instead, node.js will wait until the current thread of execution in node.js is done and then, and only then, the next event in the event queue will be pulled out and the appropriate callback for that event will get called.
So, if you have some piece of long running node.js code, it will block all other events (including timer events) until it is done and node.js can get back to pulling the next event out of the event queue.