Skip to content

事件循环相关

和浏览器绘制

demo

html
<div id="demoA">this is demoA</div>
<script>
  //一帧promise
demoA.onclick = function click3() {
  Promise.resolve().then(() => {
    demoA.textContent = 'promise'
  })
}
</script>
html
<div id="demoB">this is demoB</div>
<script>
  //一帧setTimeout
demoB.onclick = function () {
  setTimeout(() => {
    demoB.textContent = "setTimeout"
  }, 0)
}
</script>
html
<div id="demoC">this is demoC</div>
<script>
  //只有一帧1
demoC.onclick = function click1() {
  setTimeout(function setTimeout1() {
    demoC.textContent = 0
  }, 0)
  setTimeout(function setTimeout2() {
    demoC.textContent = 1
  }, 0)
}
</script>
html
<div id="demod">this is demoD</div>
<script>
  //两帧0,1
demod.onclick = function click1() {
  setTimeout(function setTimeout1() {
    demoC.textContent = 0
  }, 0)
  setTimeout(function setTimeout2() {
    demoC.textContent = 1
  }, 1)
}
</script>
html
<div id="demoE">this is demoE</div>
<script>
//两帧demoD Promise1 ->demoD Promise2
demoE.onclick = function () {
  demoE.textContent = 0
  Promise.resolve().then(() => {
    console.log('demoD Promise1')
    demoE.textContent = 'demoD Promise1'
  })
  setTimeout(() => {
    demoE.textContent = 1
    Promise.resolve().then(() => {
      console.log('demoD Promise2')
      demoE.textContent = 'demoD Promise2'
    })
  }, 0)
}
</script>
html
<div id="demoF">this is demoF</div>
<script>
//绘制了0,1,2 三帧
const raf = function () {
  requestAnimationFrame(() => {
    demoF.textContent = t
    Promise.resolve().then(() => {
      t++
      if (t < 3) raf()
    })
  })
}
demoF.onclick = function () {
  raf()
}
</script>