setTimeout(function () {
console.log(1)
}, 0);
new Promise(function executor(resolve) {
resolve();
}).then(function () {
console.log(2);
});
With the above code, why is the result 2,1 instead of 1,2?
Isn’t setTimeout added to the task queue first?
In terms of specifications,
setTimeout
has a minimum time of 4ms, which means that no matter how much you set, there must be at least an interval of 4ms before running the callback inside it (of course, whether the browser follows this specification is another story) thing). The asynchrony ofPromise
does not have this problem.In terms of specific implementation, the two asynchronous queues are different. The asynchronous queue where
Promise
is located has a higher priority.For details, you can read this article: Looking at Event Loop, Tasks and Microtasks in JavaScript from Promise
The tasks in
Promise
will be executed at the end of the current event loop, while the tasks insetTimeout
will be executed in the next event loopI suggest you read it, and then you will understand the content around section 1.5 in "JS You Don't Know (Volume 2)". That's what I understood after reading it before.