https://blog.csdn.net/SemineLee/article/details/87215457

event loop即事件循环,是指浏览器或Node的一种解决javaScript单线程运行时不会阻塞的一种机制,也就是我们经常使用异步的原理。

例子

下面的按钮,按钮点击调用和,代码调用效果是不一样的。

  1. <div id="btn">
  2. 按钮
  3. </div>
  4. <script>
  5. var btn = document.getElementById("btn");
  6. btn.addEventListener("click", () => {
  7. Promise.resolve().then(() => console.log("Microtask1"))
  8. console.log("listener 1")
  9. });
  10. btn.addEventListener("click", () => {
  11. Promise.resolve().then(() => console.log("Microtask2"))
  12. console.log("listener 2")
  13. });
  14. btn.click()
  15. </script>

相关文章

题目

代码输出结果1

  1. const first = () => (new Promise((resovle, reject) => {
  2. console.log(3);
  3. let p = new Promise((resovle, reject) => {
  4. console.log(7);
  5. setTimeout(() => {
  6. console.log(5);
  7. resovle(6);
  8. }, 0)
  9. resovle(1);
  10. });
  11. resovle(2);
  12. p.then((arg) => {
  13. console.log(arg);
  14. });
  15. }));
  16. first().then((arg) => {
  17. console.log(arg);
  18. });
  19. console.log(4);

代码输出结果2

  1. function test() {
  2. console.log(1)
  3. setTimeout(function () { // timer1
  4. console.log(2)
  5. }, 1000)
  6. }
  7. test()
  8. setTimeout(function () { // timer1
  9. console.log(3)
  10. })
  11. new Promise(function (resolve) {
  12. console.log(4)
  13. setTimeout(function () { // timer1
  14. console.log(5)
  15. }, 100)
  16. resolve()
  17. }).then(function () {
  18. setTimeout(function () { // timer1
  19. console.log(6)
  20. }, 0)
  21. })
  22. console.log(8)

看代码说出结果3

  1. async function async1() {
  2. console.log('async1 start');
  3. await async2();
  4. console.log('async1 end');
  5. }
  6. async function async2() {
  7. console.log('async2');
  8. }
  9. console.log('script start');
  10. setTimeout(function() {
  11. console.log('setTimeout');
  12. }, 0);
  13. async1();
  14. new Promise(function(resolve) {
  15. console.log('promise1');
  16. resolve();
  17. }).then(function() {
  18. console.log('promise2');
  19. });
  20. console.log('script end');

看代码输出结果4

  1. setTimeout(() => {
  2. console.log(7);
  3. });
  4. Promise.resolve()
  5. .then(() => {
  6. console.log(0);
  7. return Promise.resolve(4);
  8. })
  9. .then((res) => {
  10. console.log(res);
  11. });
  12. Promise.resolve()
  13. .then(() => {
  14. console.log(1);
  15. })
  16. .then(() => {
  17. console.log(2);
  18. })
  19. .then(() => {
  20. console.log(3);
  21. })
  22. .then(() => {
  23. console.log(5);
  24. })
  25. .then(() => {
  26. console.log(6);
  27. });

看代码输出结果5

  1. console.log(1);
  2. Promise.resolve().then(() => {
  3. console.log(2)
  4. return Promise.resolve(3)
  5. }).then(res => {
  6. console.log(res);
  7. })
  8. console.log(4)
  9. new Promise((reslove, reject) => {
  10. console.log(5)
  11. reslove()
  12. }).then(() => {
  13. console.log(6)
  14. })
  15. console.log(7)