调用window.requestAnimationFrame(step);传入一个回调函数,回调函数接收到一个动画触发时间,在回调函数里可以再次调用window.requestAnimationFrame(step);
它是一个宏任务,但是相较于其他平行宏任务的执行时间不确定
<body><div id="box"></div><button onclick="handleToggle()">toggle</button><script>const element = document.getElementById('box');let start;let r = truefunction handleToggle() {r = !rconsole.log(r);}function step(timestamp) {if (start === undefined)start = timestamp;const elapsed = timestamp - start;//这里使用`Math.min()`确保元素刚好停在 200px 的位置。element.style.transform = `rotate(${elapsed * 1}deg)`// element.style.transform = 'translateX(' + Math.min(0.1 * elapsed, 200) + 'px)';// if (elapsed < 2000) { // 在两秒后停止动画// window.requestAnimationFrame(step);// }if (r) {window.requestAnimationFrame(step);}}window.requestAnimationFrame(step);</script></body>
