Node.js version 0.10 was released today and introduced setImmediate
. The API changes documentation suggests using it when doing recursive nextTick
As an illustration
import fs from 'fs';
import http from 'http';
const options = {
host: 'www.stackoverflow.com',
port: 80,
path: '/index.html'
};
describe('deferredExecution', () => {
it('deferredExecution', (done) => {
console.log('Start');
setTimeout(() => console.log('TO1'), 0);
setImmediate(() => console.log('IM1'));
process.nextTick(() => console.log('NT1'));
setImmediate(() => console.log('IM2'));
process.nextTick(() => console.log('NT2'));
http.get(options, () => console.log('IO1'));
fs.readdir(process.cwd(), () => console.log('IO2'));
setImmediate(() => console.log('IM3'));
process.nextTick(() => console.log('NT3'));
setImmediate(() => console.log('IM4'));
fs.readdir(process.cwd(), () => console.log('IO3'));
console.log('Done');
setTimeout(done, 1500);
});
});
will give the following output
Start
Done
NT1
NT2
NT3
TO1
IO2
IO3
IM1
IM2
IM3
IM4
IO1
I hope this can help to understand the difference.
Updated:
Callbacks deferred with
process.nextTick()
run before any other I/O event is fired, while with setImmediate(), the execution is queued behind any I/O event that is already in the queue.Node.js Design Patterns, by Mario Casciaro (probably the best book about node.js/js)