关于事件轮询

296 阅读1分钟

事件轮询(Event Loop)

  • JS是单线程的,即同一时间只能执行一个任务
  • 在JS中,任务分为同步任务和异步任务
    1. 同步任务:在主线程上执行的,形成一个执行栈,前一个任务执行完后执行后一个任务
      • 比如for循环,定时器的声明,事件绑定...
    2. 异步任务:通过回调函数实现在做任务的同时还能做其他任务
      • 比如定时器的回调,ajax的回调,事件函数
  • 异步任务又分为宏任务和微任务
    • 宏任务:setTimeout,setInterval,ajax,dom事件监听...
    • 微任务:promise,.then,async/await...

执行过程

  • 优先执行同步任务,遇到异步任务推入任务队列中,等同步任务执行完再执行任务队列中的任务,任务队列中又分宏任务和微任务,先执行微任务,再执行宏任务

练习题

console.log(1)
setTimeout(()=>{ 
    console.log(2) 
    },0)
new Promise((resolve, reject)=>{ 
    console.log(3) 
    resolve() 
    }).then(()=>{ 
    console.log(4) 
    }) 
    console.log(5)
//执行结果:1 3 5 4 2
async function fn1 (){ 
    console.log(1) 
    await fn2() 
    console.log(2) // 阻塞 
    } 
async function fn2(){ 
    console.log(3) 
    } 
fn1() 
console.log(4)
执行结果:1 3 2 4