20.EventLoop.html 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <!--
  10. js是单线程,同一个时间只能做一件事,执行顺序:自上之下执行。所以,实现异步通过eventLoop。
  11. 机制eventLoop
  12. 事件循环机制。js引擎在一次事件循环中,会先执行js线程的主任务,然后会去查找是否有微任务microtask(promise),
  13. 如果有那就优先执行微任务,如果没有,在去查找宏任务macrotask(setTimeout、setInterval)进行执行
  14. <b>浏览器eventLoop和node eventLoop</b>
  15. js是单线程的,但是ajax和setTimeout在浏览器里面会多开一个线程
  16. <b>宏任务:</b>setTimeout setInterval setImmediate(ie下 生效) MessageChannel(消息通道)
  17. <b>微任务:</b>Promise.then MutationObserver (监听dom节点更新完毕) process.nextTick()
  18. 小结:代码从上到下执行,会先执行同步的代码,再执行微任务,等到宏任务有没有到时间,
  19. 时间到了的宏任务放到宏任务队列,微任务执行完毕之后,
  20. 会从宏任务队列中取出一个宏任务会放到当前的浏览器的执行环境中执行,当前执行环境都执行完毕后,
  21. 会先去清空微任务。
  22. -->
  23. <script>
  24. // setTimeout(() => {
  25. // console.log("0");
  26. // }, 0);
  27. // new Promise((resolve, reject) => {
  28. // console.log("1"); // 1
  29. // resolve();
  30. // })
  31. // .then(() => {
  32. // console.log("2"); //微1
  33. // new Promise((resolve, reject) => {
  34. // console.log("3"); // Promise1
  35. // resolve();
  36. // })
  37. // .then(() => {
  38. // console.log("4");
  39. // })
  40. // .then(() => {
  41. // console.log("5");
  42. // });
  43. // })
  44. // .then(
  45. // () => {
  46. // console.log("6");
  47. // },
  48. // () => {}
  49. // );
  50. // new Promise((resolve, reject) => {
  51. // console.log("7"); //2
  52. // resolve();
  53. // }).then(() => {
  54. // console.log("8");
  55. // });
  56. // // 1 7 238
  57. console.log(1);
  58. setTimeout(function () {
  59. console.log(2);
  60. let promise = new Promise(function (resolve, reject) {
  61. console.log(7);
  62. resolve();
  63. }).then(function () {
  64. console.log(8);
  65. });
  66. }, 1000);
  67. setTimeout(function () {
  68. console.log(10);
  69. let promise = new Promise(function (resolve, reject) {
  70. console.log(11);
  71. resolve();
  72. }).then(function () {
  73. console.log(12);
  74. });
  75. }, 0);
  76. let promise = new Promise(function (resolve, reject) {
  77. console.log(3);
  78. resolve();
  79. })
  80. .then(function () {
  81. console.log(4);
  82. })
  83. .then(function () {
  84. console.log(9);
  85. });
  86. console.log(5);
  87. </script>
  88. </body>
  89. </html>