setTimeout(function() {
   console.log(1)
}, 0);

new Promise(function(resolve, reject) {
  console.log(2)
  for (var i = 0; i < 10000; i++) {
    if(i === 10) {console.log(10)}
       i == 9999 && resolve();
  }
   console.log(3)
}).then(function() {
   console.log(4)
})

console.log(5);Copy the code









2, 10, 3, 5, 4, 1






when


  1. SetTimeout (fn, 0) when to execute
  2. When the promise function is executed
  3. Then when to execute









1. When is setTimeout(fn, 0) executed?


















SetTimeout secrets you should know






2. When will the promise be implemented?








new Promise(function(resolve, reject) {
  console.log(2)
  for (var i = 0; i < 10000; i++) {
    if(i === 10) {console.log(10)}
       i == 9999 && resolve();
  }
   console.log(3)
})Copy the code

2 10 3






Promise
Promise constructor
synchronous






3. Then when to execute?








new Promise(function(resolve, reject) {
  console.log(2)
  for (var i = 0; i < 10000; i++) {
    if(i === 10) {console.log(10)}
       i == 9999 && resolve();
   }
   console.log(3)
}).then(function() {
   console.log(4)
})

for (var i = 0; i < 5; i++) {
   console.log('a' + i);	
}Copy the code

2 10 3 a0 a1 a2 a3 a4 4






then





setTimeout(function() {
   console.log(1)
}, 0);

new Promise(function(resolve, reject) {
  console.log(2)
   for (var i = 0; i < 10000; i++) {
    if(i === 10) {console.log(10)}
       i == 9999 && resolve();
  }
   console.log(3)
}).then(function() {
   console.log(4)
})

console.log(5);Copy the code

2, 10, 3, 5, 4, 1






when
then
setTimeout












Is setTimeout 0 really 0?






Minimum execution time
minimum delay of 4ms
0s












Macrotask and microtask









macrotasks
setTimeout, setInterval, setImmediate, I/O, UI rendering



microtasks
process.nextTick, Promise, MutationObserver






macrotask
microtask








  • First of all,setTimeoutHave been tomacrotaskQueue (will be nextmacrotaskIn the execution) in.
  • Next, it executes firstmacrotaskThe first task (synchronized code throughout the script) in, plusPromise constructorAlso synchronous (promise.thenThe pullback is pushed tomicrotaskQueue), so it prints 2, 10, and 3, and then continues at the end, printing 5
  • At this point, the first one is donemacrotask, so everything will be executed sequentiallymicrotask, that is,promise.then To print 4.
  • At this point,microtaskThe tasks in the queue have completed, so execute the restmacrotaskTasks in the queue, which issetTimeout, so print out 1.



Synchronization code (including promise's constructor) -> promise.then -> setTimeout















Developer.mozilla.org/zh-CN/docs/…



www.ruanyifeng.com/blog/2014/1…



Juejin. Cn/post / 684490…



www.zhihu.com/question/36…



Developer.mozilla.org/zh-CN/docs/…



Jakearchibald.com/2015/tasks-…



Stackoverflow.com/questions/3…