异步编程(二)

2019-04-13  本文已影响0人  frameworkofthin

setTimeout

setTimeout设置的时间一定准确吗?为什么

console.log(1)
setTimeou(() => console.log(2), 0)
console.log(3)

1 3 2

requestAnimationFrame

特点

作用

题目一

利用requestAnimationFrame写一个进度条

答案(自己写)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    #process {
      width: 0px;
      background: #f0f;
      height: 30px;
      transition: all 0.5;
    }
  </style>
</head>
<body>
  <div id="process"></div>
  <script>
    let timer = null
    let render = () => {
      timer = window.requestAnimationFrame(() => {
        const width = document.getElementById('process').style.width || 0
        const nextWidth = parseInt(width) + 1
        if (nextWidth < 1000) {
          document.getElementById('process').style.width = `${nextWidth}px`
          render()
        }
        else window.cancelAnimationFrame(timer)
      })
    }
    render()
  </script>
</body>
</html>

题目二

使用requestAnimationFrame模拟一个setTimeout


上一篇 下一篇

猜你喜欢

热点阅读