Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS - setTimeout(fn,0) vs setImmediate(fn)

What is the difference between those two, and when will I use one over the other?

like image 327
Shlomi Schwartz Avatar asked Jun 09 '14 09:06

Shlomi Schwartz


People also ask

Why is setTimeout 0 used?

Invoking setTimeout with a callback, and zero as the second argument will schedule the callback to be run asynchronously, after the shortest possible delay - which will be around 10ms when the tab has focus and the JavaScript thread of execution is not busy.

What is the difference between process nextTick () and setImmediate ()?

process. nextTick() is used to schedule a callback function to be invoked in the next iteration of the Event Loop. setImmediate() method is used to execute a function right after the current event loop finishes.

What is setImmediate in node JS?

The setImmediate function is used to execute a function right after the current event loop finishes. In simple terms, the function functionToExecute is called after all the statements in the script are executed. It is the same as calling the setTimeout function with zero delays.

Does setTimeout work in node JS?

setTimeout is a built-in Node. js API function which executes a given method only after a desired time period which should be defined in milliseconds only and it returns a timeout object which can be used further in the process.


2 Answers

setTimeout is simply like calling the function after delay has finished. Whenever a function is called it is not executed immediately, but queued so that it is executed after all the executing and currently queued eventhandlers finish first. setTimeout(,0) essentially means execute after all current functions in the present queue get executed. No guarantees can be made about how long it could take.

setImmediate is similar in this regard except that it doesn't use queue of functions. It checks queue of I/O eventhandlers. If all I/O events in the current snapshot are processed, it executes the callback. It queues them immediately after the last I/O handler somewhat like process.nextTick. So it is faster.

Also (setTimeout,0) will be slow because it will check the timer at least once before executing. At times it can be twice as slow. Here is a benchmark.

var Suite = require('benchmark').Suite var fs = require('fs')  var suite = new Suite  suite.add('deffered.resolve()', function(deferred) {   deferred.resolve() }, {defer: true})  suite.add('setImmediate()', function(deferred) {   setImmediate(function() {     deferred.resolve()   }) }, {defer: true})  suite.add('setTimeout(,0)', function(deferred) {   setTimeout(function() {     deferred.resolve()   },0) }, {defer: true})  suite .on('cycle', function(event) {   console.log(String(event.target)); }) .on('complete', function() {   console.log('Fastest is ' + this.filter('fastest').pluck('name')); }) .run({async: true}) 

Output

deffered.resolve() x 993 ops/sec ±0.67% (22 runs sampled) setImmediate() x 914 ops/sec ±2.48% (57 runs sampled) setTimeout(,0) x 445 ops/sec ±2.79% (82 runs sampled) 

First one gives idea of fastest possible calls. You can check yourself if setTimeout gets called half as many times as other. Also remember setImmediate will adjust to your filesystem calls. So under load it will perform less. I don't think setTimeout can do better.

setTimeout is un-intrusive way of calling functions after some time. Its just like its in the browser. It may not be suited for server-side (think why I used benchmark.js not setTimeout).

like image 166
user568109 Avatar answered Sep 17 '22 10:09

user568109


A great article about how event loop works and clears some misconceptions. http://voidcanvas.com/setimmediate-vs-nexttick-vs-settimeout/

Citing the article:

setImmediate callbacks are called after I/O Queue callbacks are finished or timed out. setImmediate callbacks are placed in Check Queue, which are processed after I/O Queue.

setTimeout(fn, 0) callbacks are placed in Timer Queue and will be called after I/O callbacks as well as Check Queue callbacks. As event loop, process the timer queue first in each iteration, so which one will be executed first depends on which phase event loop is.

like image 42
Aman Gupta Avatar answered Sep 18 '22 10:09

Aman Gupta