<!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>
.progress {
width: 0;
height: 20px;
line-height: 20px;
background: yellowgreen;
}
</style>
</head>
<body>
<div id="bar" class="progress">0%</div>
<button id="btn">setTimeout</button>
<button id="btn1">setInterval</button>
<button id="btn2">requestAnimationFrame</button>
<script>
// 使用setTimeout,第一次執(zhí)行完定時(shí)回調(diào),全部執(zhí)行完調(diào)用clearTimeout清除定時(shí)器
btn.onclick = function(){
console.time('setTimeout')
var progress = 0
var timer = setTimeout(function fn() {
progress ++
if(progress <= 100){
bar.style.width = progress + 'px'
bar.innerHTML = progress + '%'
timer = setTimeout(fn, 1000/60)
}else{
console.timeEnd('setTimeout')
clearTimeout(timer)
}
}, 1000/60)
}
// 使用setInterval,全部執(zhí)行完調(diào)用clearInterval清除定時(shí)器
btn1.onclick = function(){
console.time('setInterval')
var progress = 0
var timer = setInterval(function fn() {
progress ++
if(progress <= 100){
bar.style.width = progress + 'px'
bar.innerHTML = progress + '%'
}else{
console.timeEnd('setInterval')
clearInterval(timer)
}
}, 1000/60)
}
// 使用requestAnimationFrame,用法與settimeout相似
// 第一次執(zhí)行完調(diào)用requestAnimationFrame,但不需要設(shè)置時(shí)間,全部執(zhí)行完調(diào)用cancelAnimationFrame
btn2.onclick = function(){
console.time('requestAnimationFrame')
var progress = 0
var timer = requestAnimationFrame(function fn(){
progress ++
if(progress <= 100){
bar.style.width = progress + 'px'
bar.innerHTML = progress + '%'
timer = requestAnimationFrame(fn)
}else{
console.timeEnd('requestAnimationFrame')
cancelAnimationFrame(timer)
}
})
}
// 理論動(dòng)畫(huà)時(shí)長(zhǎng)約1666ms,setTimeout和setInterval設(shè)置60fps,requestAnimationFrame默認(rèn)
// setTimeout: 1700.072021484375ms
// setInterval: 1617.007080078125ms
// requestAnimationFrame: 1664.283203125ms
// 結(jié)論:setTimeout和setInterval動(dòng)畫(huà)執(zhí)行誤差約20%-30%,requestAnimationFrame誤差約1%
</script>
</body>
</html>