time 0m
time 2m05s
<div id="box" style="width: 100px;height: 100px;background-color: red"></div><script !src="">const element = document.getElementById('box');let start;function step(timestamp) {if (start === undefined)start = timestamp;const elapsed = timestamp - start;//这里使用`Math.min()`确保元素刚好停在 200px 的位置。element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)';if (elapsed < 2000) { // 在两秒后停止动画window.requestAnimationFrame(step);}}window.requestAnimationFrame(step);</script>
分析代码
<div id="box" style="width: 100px;height: 100px;background-color: red"></div><script !src="">const element = document.getElementById('box');let start;function step(timestamp) {/*时间戳*/// console.log(timestamp);if (start === undefined){start = timestamp;}/*start是step第一次执行的时间,都是一样的*/// console.log(start);/*时间戳在增加,时间戳减去第一次执行的时间,可以得出到底流失了多少时间*/const elapsed = timestamp - start;//这里使用`Math.min()`确保元素刚好停在 200px 的位置。element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)';if (elapsed < 2000) { // 在两秒后停止动画window.requestAnimationFrame(step);}}/*** 调用了requestAnimationFrame,会执行step函数*/window.requestAnimationFrame(step);// step()//不会运动</script>
setInterval与requestAnimationFrame
time 13m07s
<div id="box" style="width: 100px;height: 100px;background-color: red"></div><script !src="">const element = document.getElementById('box');let px = 0;let t = null;function step() {px++;element.style.transform = 'translateX(' + px + 'px)';if (px > 200) {clearInterval(t);t = null;}}// 刷新率1s刷新60次t = setInterval(step, 1000 / 60);</script>
time 16m36s
<script !src="">let t = null,i = 0,j = 0;t = setInterval(() => {console.log(i++);}, 1000)</script>
即使浏览器最小化,在后台,也可以运行
requestAnimationFrame在后台,不可以运行,这样可以节省性能
<script !src="">let t = null,i = 0,j = 0;t = setInterval(() => {console.log(i++);}, 1000);function step() {setTimeout(()=>{window.requestAnimationFrame(step);console.log('requestAnimationFrame:',j++);},1000);}window.requestAnimationFrame(step);</script>


