window.requestAnimationFrame(callback)/ cancelAnimationFrame(callback)
window. requestAnimationFrame(callback)创建一个自定义执行动画,
cancelAnimationFrame(callback)取消该自定义动画
callback需要穿进去的回调函数(自定义),
与window.setInterval定时器类似,又不相同。在更新动画时,相比setInterval定时器,更推荐使用requestAnimationFrame。
官方文档释义:window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行。
☆注意:若你想在浏览器下次重绘之前继续更新下一帧动画,那么回调函数自身必须再次调用window.requestAnimationFrame()。
let targetBox = window.document.getElementById("target-box");
let container = window.document.getElementById("container");
let left = parseInt(getComputedStyle(targetBox).left);
let counter=0;
let tempLeft=left;
var start = null;
function interval(timestamp){
if (!start) start = timestamp;
var progress = timestamp - start;
counter++;
left+=10;
console.log(counter);
targetBox.style.left=`${
left}px`;
if(counter>100){
counter=0;
left = tempLeft;
}
if (progress < 20000) {
window.requestAnimationFrame(interval);
}
}
window.requestAnimationFrame(interval);
<div class="target-box" id="target-box"></div>
<div class="container" id="container"></div>
.body {
position: relative;
}
.container {
width: 200px;
height: 300px;
background: rgba(66, 41, 11, 0.239);
}
.target-box {
position: absolute;
top: 300px;
left: 300px;
width: 30px;
height: 30px;
background: aquamarine;
}
如前面所说,需要在回调函数体内再次调用
window.requestAnimationFrame(callback);
let counter = 0;
let start = null;
function animation(timestamp){
if(!start) start = timestamp;
let progress = timestamp - start;
counter ++;
if(progress < 20000)
window.requestAnimationFrame(animation);
console.log(counter);
}
window.requestAnimationFrame(animation);
当我们想在某个计数器节点取消动画执行,使用cancelAnimationFram(callback);即可
let counter = 0;
let start = null;
function animation(timestamp){
if(!start) start = timestamp;
let progress = timestamp - start;
counter ++;
if(counter>9){
window.cancelAnimationFrame(animation);
}else{
if(progress < 20000)
window.requestAnimationFrame(animation);
}
console.log(counter);
}
window.requestAnimationFrame(animation);