setTimeout
setTimeout设置的时间一定准确吗?为什么
- 不一定。
- setTimeout是异步函数,会被放入到任务队列中去。只有当前的主任务执行完成后,才会去读取任务队列中的事件,再去执行相对应的回调函数。
- 如果主任务处理的时间过长,就会导致时间到了以后也没有执行对应的回调函数
console.log(1)
setTimeou(() => console.log(2), 0)
console.log(3)
1 3 2
requestAnimationFrame
特点
- 根据系统的频率进行执行(16.6ms执行一次)
- 定时是精准的
作用
- 主要用于制作动画
- setTimeout和setInterval都会因为时间的不精确,会导致动画要么过度频繁、要么卡顿。而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
网友评论