JS魔法堂:函数节流(throttle)与函数去抖(debounce)
warning:
这篇文章距离上次修改已过200天,其中的内容可能已经有所变动。
// 函数节流:确保一定时间内只执行一次函数
function throttle(fn, threshhold, scope) {
threshhold || (threshhold = 250);
var last,
timer;
return function () {
var context = scope || this;
var now = +new Date(),
args = arguments;
if (last && now - last < threshhold) {
// 如果足够的时间没有过去,则清除定时器并重新设定执行时间
clearTimeout(timer);
timer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
// 如果时间到了,执行函数并重置执行时间
last = now;
fn.apply(context, args);
}
};
}
// 函数去抖:在函数执行完后等待一段时间,如果在这段时间内没有再次触发,则不再执行
function debounce(fn, delay) {
var timer = null;
return function () {
var context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
};
}
// 使用示例
var myFunc = function() {
console.log('Function triggered!');
};
// 节流
window.addEventListener('resize', throttle(myFunc, 1000));
// 去抖
window.addEventListener('scroll', debounce(myFunc, 500));
这段代码定义了两个函数throttle
和debounce
,它们可以用来控制函数的执行频率。throttle
用于限制一个函数在一定时间内只能执行一次,而debounce
则是在函数执行完后等待一段时间,如果在这段时间内没有再次触发,则不再执行该函数。这两种方式在不同的场景下都有其用处,例如滚动和调整浏览器大小时的事件监听。
评论已关闭