防抖(debounce)
当持续触发事件时,在一定的时间段内,只有最后一次触发的事件才会执行。
function debounce(fn, wait) {
var timer = null;
return function () {
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(fn, wait);
}
}
function handle() {
console.log('防抖处理!');
}
window.addEventListener('scroll', debounce(handle, 1000));
节流(throttle)
当持续触发事件时,已执行的事件在一定时间段内不会再次执行。实现节流有
-
时间戳
var throttle = function (func, delay) { var prev = Date.now(); return function () { var now = Date.now(); if (now - prev >= delay) { func(); prev = Date.now(); } } } function handle() { console.log('节流处理!'); } window.addEventListener('scroll', throttle(handle, 1000));
-
定时器
var throttle = function (func, delay) { var timer = null; return function () { if (!timer) { timer = setTimeout(function () { func(); timer = null; }, delay); } } } function handle() { console.log('节流处理!'); } window.addEventListener('scroll', throttle(handle, 1000));
总结
- 函数防抖和节流都是防止某一事件被频繁触发;
- 区别:防抖是将多次执行变为最后一次执行,节流是将多次执行变为一段时间只执行一次。
- 应用场景:窗口resize、页面scroll、拖拽、限时抢购、实时搜索等。