(进阶)浏览器优化之防抖与节流
-
浏览器对事件的优化
一般我们屏幕的帧率是每秒60帧,也就是60fps,但是某些事件触发的频率超过了这个数值,比如 wheel, mousewheel,mousemove,pointermove,touchmove,这些连续性的事件一般每 秒会触发60~120次,假如每一次触发事件都将事件发送到主线程处理,由于屏幕的刷新速率相对 来说较低,这样使得主线程会触发过量的命中测试以及JS代码,使得性能有了没必要的损耗。 出于优化的目的,浏览器会合并这些连续的事件,延迟到下一帧渲染是执行,也就是 requestAnimationFrame之前。
防抖
function debounce(callback,wait){ let timerId = null; return function(event){ if (timerId !== null){ clearTimeout(timerId); } timerId = setTimeout(()=>{ callback.call(this,event); timerId = null; },wait) } } document.querySelector('input').addEventListener('keydown',debounce(function(e){ console.log(this.value) },500))
节流
function throttle(callback,wait){ let start = 0; return function(){ let now = Date.now(); if (now - wait > start){ callback.call(this,event); start = now; } } } window.addEventListener('scroll',throttle(function(e){ console.log(Date.now()); },500))