setImmediate method has been part of node.js for quite sometime now and is surprisingly only supported by Internet Explorer 10, with no support from Safari, Chrome and Firefox as of writing this.
In this post, we will see what does it do and what is the reason/need for having something like
setImmediate on browsers and as well as on server.
What does setImmediate() do?
In case of browsers, what setImmediate does is to tell the browser that you want to execute some piece of code after it has finished executing all the tasks in its event loop, thus immediate callbacks.
Basically, if we look
setImmediate solves a very common problem that exists with
setTimeout which is the 4 ms per callback resolution with HTML5 browsers today.
Node.js has a method
process.nextTick which already gave developers a hard time understanding its actual working and use-case. We won't be going into much detail about it here. Though brefiely what it does is executes a callback before the next cycle of event loop.
setImmediate in the v0.9 and with a purpose just opposite to that of
process.nextTick. Also opposite to its name,
setImmediate executes a callback on the next cycle of the event loop and yeilds back to the event loop for any I/O. Looks confusing right, mainly due to the names.
Need for setImmediate():
setInterval API's. Though that greatly hampered the power consumption and increased the CPU utilization inturn decreasing performance. HTML5 even recommended to have 250 callbacks per second compared to the HTML4 version of 64 callbacks per second.
What setImmediate has done on browsers is to allow developers to break from long running tasks and recieve a callback as soon as the browser finishes executing any pending work on its event loop, thus increasing the CPU utilization without effecting the power consumption.
Surprisingly, the method has faced alot of oppose outside of Microsoft which is the only one who has implemented in their IE browsers. Mozilla and WebKit both seem reluctant to make it a standard with arguments that are already being debated by the community.
Will be interesting to see what shape does it take, till then tada. Let me know what you guys think about setImmediate.