Green
Green

Reputation: 30785

What is there so exceptional about timers in Node.js?

I want to understand Event Loop better. I read documents, articles, Node.js' API docs. Almost all of them separate Timers:

setImmediate():

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

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

process.nextTick():

process.nextTick(callback[, arg][, ...])#

This is not a simple alias to setTimeout(fn, 0), it's much more efficient. It runs before any additional I/O events (including timers) fire in subsequent ticks of the event loop.

Why? What is so exceptional about timer functions in Node.js in the context of Event Loop?

Upvotes: 0

Views: 97

Answers (2)

pspi
pspi

Reputation: 11917

These all relate to having really fine grained control over the asynchronous execution of the callback.

The nextTick() function is executed the soonest to the point where it's called. It got its name from event loop "tick". Tick represents full turn of the event loop where different sort of events such as timers, io, network are exhausted once. Even though the name today is confusing since it has changed semantics over node versions. The nextTick() callback is executed in the same tick as the calling code. Adding more nextTick()s in the nextTick() callback function aggregates them and they are called in the same tick.

The setImmediate() gives the second closest execution. It's almost identical to setTimeout(0) but it is called before all traditional setTimeout() and setInterval() timers. It is processed as the first thing at the beginning of the next tick. You get sort of a fast lane of asynchronous execution that is privileged over the traditional setInterval() and setTimeout(). Adding more setImmediate() callbacks in setImmediate() itself defers them to next tick and they are not executed in the same tick in contrast to how nextTick()s are. This setImmediate() functionality was originally the semantics for nextTick(), hence the name nextTick().

The setTimeout() and setInterval() work then as expected, having the third closest exeuction point (or later if the timeouts are long).

Upvotes: 1

Kaicui
Kaicui

Reputation: 3863

Put simply, the order they called is:nextTick()-->setImmediate()-->setTimeout(fn, 0)

Upvotes: 1

Related Questions