A
A
Alex Ozerov2021-07-06 14:05:01
Node.js
Alex Ozerov, 2021-07-06 14:05:01

Why is setTimeout faster than setImmediate?

The execution sequence is indicated in the comments

console.log('console.log 1')//1
setTimeout(() => console.log('setTimeout'), 0)//3
setImmediate(() => console.log('setImmediate'))//4
console.log('console.log 2')//2

and another example:
console.log('console.log 1')//1
fs.readFile('./views/about.html', 'utf8', (err,data) => {
    setTimeout(() => console.log('setTimeout'), 0)//4
    setImmediate(() => console.log('setImmediate'))//3
})
console.log('console.log 2')//2

In the first case, the timeout is faster because in the event loop timers take precedence over the "Check" loop, but also setImmediate should take precedence over setTimeout. In general, help to understand why.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
Lynn "Coffee Man", 2021-07-06
@alex_vma

Because so lucky. This is not a guarantee.
https://nodejs.org/en/docs/guides/event-loop-timer...

For example, if we run the following script which is not within an I/O cycle (ie the main module), the order in which the two timers are executed is non-deterministic, as it is bound by the performance of the process: [...]
However, if you move the two calls within an I/O cycle, the immediate callback is always executed first:

A
Aetae, 2021-07-06
@Aetae

Here is a good answer, puts everything on the shelves (specific answer in the comments):
https://stackoverflow.com/questions/55467033/diffe...
In Node, there are 4 queues for essentially the same thing (2 from the node itself 2 from v8). :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question