js中的requestAnimationFrame与cancelAnimationFrame
使用setTimout()或者setInterval()这两个定时器函数实现动画是最为原始简单的方式,但是缺点也很大,最重要的一个缺点就是有可能出现丢帧现象。
requestAnimationFrame
requestAnimationFrame会把每一帧中的所有DOM操作集中起来,在一次重绘或回流中就完成,并且重绘或回流的时间间隔紧紧跟随浏览器的刷新频率,一般来说,这个频率为每秒60帧。
cancelAnimationFrame
cancelAnimationFrame与clearInterval用法一样,用来清除动画
效果如图:
代码实例如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
<style>
#box{
width: 80%;
margin:auto
}
#pro {
width:0px;
height:20px;
background:deepskyblue;
color:#FFF;
border-radius: 10px;
padding:0 10px;
}
button{
padding: 10px;
border:1px solid deepskyblue;
color:#fff;
background:deepskyblue;
outline: none;
margin: 10px 1px;
border-radius: 3px;
}
</style>
</head>
<body>
<div id="box">
<div id="pro">0%</div>
<button id="run">重新开始</button>
<button id='stop'>停止动画</button>
</div>
</body>
<script>
var ele = document.getElementById("pro");
var progress = 0;
var timer;
function step() {
progress += 1;
ele.style.width = progress + "%";
ele.innerHTML = progress + "%";
if (progress < 100) {
timer = requestAnimationFrame(step);
}
}
requestAnimationFrame(step);
//点击重新开始按钮,再次调用清除宽度再次调用
document.getElementById("run").addEventListener("click", function () {
ele.style.width = "0px";
progress = 0;
requestAnimationFrame(step);
});
//点击停止动画按钮,cancelAnimationFrame停止动画
document.getElementById("stop").addEventListener("click", function () {
cancelAnimationFrame(timer);
});
</script>
</html>