专栏名称: hpoenixf
前端
目录
相关文章推荐
蒲公英Ouryao  ·  出厂药品「竟不做」含量检测!!! ·  23 小时前  
解螺旋  ·  官宣!DeepSeek正式接入PubMed! ... ·  2 天前  
51好读  ›  专栏  ›  hpoenixf

任务队列、事件循环与定时器

hpoenixf  · 掘金  ·  · 2018-05-27 02:04

正文

请到「今天看啥」查看全文



用代码验证一下

setTimeout(() => {
    console.log('t0')
    Promise.resolve().then(res => {
      console.log('p0')
    })
  })
  let i = 0
  function raf () {
    console.log(i)
    document.querySelector('div').style.width = i * 20 + 'px'
    Promise.resolve().then(res => console.log('p' + i))
    setTimeout(() => {
      console.log('t' + i)
      if (i === 1) {
        document.querySelector('div').style.background = 'red'
        document.querySelector('div').style.height = '50px'
      }
      if (i === 2) {
        let j = 0
        while (j++ < 1000000000) {
        }
        document.querySelector('div').style.background = 'blue'
        document.querySelector('div').style.height = '300px'
      }
      if (i === 3) {
        document.querySelector('div').style.width = '40px'
      }
      Promise.resolve(3).then(res => {
        console.log('tp' + i)
      })
    })
    if (++i <= 10) {
      requestAnimationFrame(raf)
    }
  }
  requestAnimationFrame(raf)

输出结果为 t0,p0,0,p1,t1,tp1,1,p2,t2,tp2,2,p3,p4,t4,tp4,t4,tp4,4...

使用chrome dev tool的performance查看过程







请到「今天看啥」查看全文