背景
在了解宏任务的时候了解到requestAnimationFrame,cancelAnimationFrame,然后做了实践。
方法
-
requestAnimationFrame(callback)
即屏幕刷新率,执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画,回调函数执行次数通常是每秒60次。
-
cancelAnimationFrame
取消一个先前通过调用window.requestAnimationFrame()方法添加到计划中的动画帧请求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<style>
.content {
width: 100%;
}
.progress {
width: 0;
height: 20px;
background-color: aqua;
border-radius: 10%;
}
.stop,
.reset {
width: 150px;
outline: none;
height: 40px;
}
.stop {
background: #ff0;
}
.reset {
background: #654565;
}
</style>
<div class="content">
<div class="progress">0%</div>
<button class="stop">停止</button>
<button class="reset">重置</button>
</div>
<script>
let dom = document.getElementsByClassName('progress')[0];
let stop = document.getElementsByClassName('stop')[0];
let reset = document.getElementsByClassName('reset')[0];
let num = 0;
var timer;
function run() {
num += 1;
dom.style.width = num + '%';
dom.innerHTML = num + '%';
if (num < 100) {
timer = requestAnimationFrame(run)
}
}
requestAnimationFrame(run);
stop.addEventListener('click', function () {
cancelAnimationFrame(timer)
})
reset.addEventListener('click', function () {
num = 0;
requestAnimationFrame(run)
})
</script>
</body>
</html>