Answer the question
In order to leave comments, you need to log in
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
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
Answer the question
In order to leave comments, you need to log in
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:
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question