这篇文章很短。
在前一篇文章中,我们讨论了在另一篇文章中讨论的几个技术的API实现。
在这篇文章中,我们将看看requestAnimationFrame
。
当我们有一些重绘任务的时候,我们使用requestAnimationFrame
– 这将改变屏幕上的内容。但这只是工作的一般方式。
function render() { // do something window.requestAnimationFrame(render); } window.requestAnimationFrame(render);
HighResTimeStamp
requestAnimationFrame
的问题是它不强制一个回调速度 – 只定义了它的上限。正如MDN所说:>回调的数量通常是每秒60次,根据W3C的建议,通常会匹配在大多数浏览器的显示刷新率。
解决方案很容易。
requestAnimationFrame
传递一个参数到回调函数。它是一个以毫秒为单位的。
因此,我们可以使用requestAnimationFrame
作为 setTimeout
的替代方法,来实现我们的Throttle。
function throttle(fn, delta, context) { return function() { var args = arguments; var then = 0; function repeat(now) { requestAnimationFrame(repeat); if (now - then >= delta) { then = now; fn.call(context, args); } } requestAnimationFrame(repeat); } }
这样,使用 requestAnimationFrame 实现 Throttle。
PS:我为这系列文章中提到的3+1技术创建了一个gist。你可以在。
翻译自:
最新评论
写的挺好的
有没有兴趣翻译 impatient js? https://exploringjs.com/impatient-js/index.html
Flexbox playground is so great!
感谢总结。
awesome!
这个好像很早就看到类似的文章了
比其他的教程好太多了
柯理化讲的好模糊…没懂