js的一些基本知识点

1、js中的执行机制、event-loop

众所周知,js是一门单线程语言,而js中将任务分为同步和异步任务、异步任务;而异步任务又分为宏任务(setTimeout. setInterval等)和异步任务(promise.then  process.nextick等),而微任务优先级大于宏任务

同步任务会进入主线程、异步任务会根据任务类型分别进入宏任务、微任务队列中。

1、当执行主线程的时候,遇到宏任务则将宏任务放进宏任务队列中,遇到微任务则将微任务放进微任务队列中

2、当主线程执行完之后,会去遍历微任务队列,这时候会先将队列的第一个微任务取出,作为主线程执行,如遇到宏任务则将宏任务放进宏任务队列中,遇到微任务则将微任务放进微任务队列中;直到该线程跑完,会遍历微任务队列的下一个事件,执行同上面的操作

3、当微任务队列遍历完之后,会去遍历宏任务队列,这时候会将第一个宏任务事件取出,作为主线程,如遇到宏任务则将宏任务放进宏任务队列中,遇到微任务则将微任务放进微任务队列中;当该主线程执行完,会执行2、3步骤;

4、当执行完3步骤之后,会取出宏任务的下一个事件,重复3步骤,直到,宏任务事件队列遍历完

即:执行主线程,遇到宏任务,将其放进宏任务队列中;遇到微任务,将其放进微任务队列中;

当主线程执行完,会先去遍历微任务,每一个微任务都会执行:遇到宏任务,将其放进宏任务队列中、遇到微任务,将其放进微任务队列中。直到微任务队列遍历完

这时候会去遍历宏任务队列,同样每一个宏任务都会执行遇到宏任务,将其放进宏任务队列中、遇到微任务,将其放进微任务队列中;当前主线程跑完,会先去执行遍历微任务队列,若其为空,则遍历宏任务队列下一个事件,直到宏任务队列遍历完

看个例子:

<html>
  <body>
    <script>
      console.log('1');

      setTimeout(function() {
          console.log('2');
          new Promise(function(resolve) {
              console.log('4');
              resolve();
          }).then(function() {
            setTimeout(function() {
              new Promise(resolve => {
                console.log(5)
                resolve()
              }).then(() => {
                console.log(6)
                setTimeout(function() {
                  console.log(7)
                })
              })
            })
            console.log('8')
          })
      })
      new Promise(function(resolve) {
          console.log('9');
          resolve();
      }).then(function() {
          console.log('10')
          setTimeout(function() {
            console.log(11)
            new Promise(resolve => {
              console.log(12)
              resolve()
            }).then(() => {
              console.log(13)
            })
          })
      })

      setTimeout(function() {
          console.log('14');
          new Promise(function(resolve) {
              console.log('15');
              resolve();
          }).then(function() {
            console.log('16')
            new Promise(resolve => {
              console.log(17)
            })
            setTimeout(function() {
              console.log(18)
            })
          })
      })
    </script>
  </body>
</html>

输出结果:

test.html:4 1
test.html:27 9
test.html:30 10
test.html:7 2
test.html:9 4
test.html:23 8
test.html:43 14
test.html:45 15
test.html:48 16
test.html:50 17
test.html:32 11
test.html:34 12
test.html:37 13
test.html:14 5
test.html:17 6
test.html:53 18
test.html:19 7

参看文章:

JavaScript开发者应懂的33个概念:https://github.com/stephentian/33-js-concepts/blob/master/README.md

猜你喜欢

转载自blog.csdn.net/tangxiujiang/article/details/116899697