30_eventloop.html 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. <script>
  10. // promise 可以直接后边写 then和catch方法
  11. // new Promise((resolve,reject)=>{
  12. // resolve("3")
  13. // }).then((res)=>{
  14. // console.log(res);
  15. // }).catch((err)=>{
  16. // console.log(err);
  17. // })
  18. // 事件循环
  19. // 事件循环的执行顺序是:
  20. // js先执行同步代码 如果运行过程中遇到异步操作,会将异步操作放到任务队列中
  21. // 等同步代码执行完毕后,会从任务队列中取任务执行 (谁处于待运行状态)
  22. // 如果任务队列中有多个异步任务可以运行状态,那么js在执行时会有一个优先级
  23. // 优先级分为(宏任务和微任务)宏任务:setTimeout、setInterval 微任务:Promise.then
  24. // 先执微任务,再执行宏任务
  25. // 如果执行中再次遇到异步任务,会将异步任务放到任务队列中,等待后续执行
  26. // 重复以上过程,直到任务队列中没有任务可执行
  27. // 这个过程称为事件循环 (event loop)
  28. console.log("1");
  29. setTimeout(() => {
  30. console.log("2");
  31. }, 0);
  32. new Promise((resolve, reject) => {
  33. setTimeout(() => {
  34. resolve("3")
  35. }, 0);
  36. }).then((res) => {
  37. console.log(res);
  38. })
  39. console.log("4");
  40. </script>
  41. </body>
  42. </html>