我们会对一些触发频率较高的事件进行监听,(如:resize scroll keyup事件)
如果在回调里执行高性能消耗的操作(如反复操作dom, 发起ajax请求等),反复触发时会使得性能消耗提高,浏览器卡顿,用户使用体验差。
或者我们需要对触发的事件延迟执行回调,此时可以借助throttle/debounce函数来实现需求。
throttle: 节流函数
在一个时间段内只执行一次
debounce:防抖函数
连续触发事件的时候,事件监听函数不会立即执行,而是等我们一段时间内不再触发事件的时候,再执行事件监听函数。
throttle函数实现
function throttle (func, wait) { var lastTime = 0; return function () { var time = Date.now(); if (time - lastTime >= wait) { func(); lastTime = time; }; }; }; // handler 是事件监听函数 var handler = function () { console.log('throttle'); }; window.onscroll = throttle(handler, 300);
debounce函数实现
function debounce (func, wait) { var timer = null; return function () { clearTimeout(timer); timer = setTimeout(func, wait); }; }; // handler 是事件监听函数 var handler = function () { console.log('debounce'); }; window.onscroll = debounce(handler, 300);