Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

priority between setTimeout and setImmediate

I read this on the node documentation :

setImmediate(callback, [arg], [...])

To schedule the "immediate" execution of callback after I/O events callbacks and before setTimeout and setInterval

However, I see the opposite. setTimeout is executed before setImmediate. Does someone have an explenation for this behavior, or any documentation on the node event loop ?

Thanks :)

code :

var index = 0;

function test(name) {
    console.log((index++) + " " + name);
}

setImmediate(function() {
    test("setImmediate");
})

setTimeout(function() {
    test("setTimeout");
}, 0);

process.nextTick(function() {
    test("nextTick");
})

test("directCall");

output :

0 directCall
1 nextTick
2 setTimeout
3 setImmediate
like image 892
etnbrd Avatar asked Apr 24 '14 12:04

etnbrd


People also ask

What is the difference between setImmediate () and setTimeout ()?

setImmediate() and setTimeout() are similar, but behave in different ways depending on when they are called. setImmediate() is designed to execute a script once the current poll phase completes. setTimeout() schedules a script to be run after a minimum threshold in ms has elapsed.

Which is better setTimeout or setInterval?

setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.

Which is faster setTimeout or promise?

Promises are faster than setTimeout. Resolved!

Why promises are faster than setTimeout?

Because of the event loop priorities dequeuing jobs from the job queue (which stores the fulfilled promises' callbacks) over the tasks from the task queue (which stores timed out setTimeout() callbacks).


1 Answers

You should check this github issue

The event loop cycle is timers -> I/O -> immediates, rinse and repeat. The documentation is correct but incomplete: it doesn't mention that when you haven't entered the event loop yet (as is the case in your example), then timers come first - but only on the first tick. (In master. To complicate matters, things work slightly less deterministic in v0.10.)

like image 116
Frédéric GRATI Avatar answered Oct 18 '22 20:10

Frédéric GRATI