本文深入解析 JavaScript 中节流(Throttle)与防抖(Debounce)的核心原理,提供完整的原生代码实现。通过对比代码逻辑,阐述两者在高频事件触发场景下的不同行为机制,并附带包含随机延迟调用的测试用例,帮助开发者根据实际需求选择合适的优化策略。
节流函数原理与实现
节流(Throttle)的主要作用是忽略特定时间窗口内的重复调用,适用于触发频率较高且处理逻辑较为沉重的场景。
具体实现代码如下:
var throttle = function (func, threshold, alt) {
var last = Date.now();
threshold = threshold || 100;
return function () {
var now = Date.now();
if (now - last < threshold) {
if (alt) {
alt.apply(this, arguments);
}
return;
}
last = now;
func.apply(this, arguments);
};
}; 防抖
防抖函数原理与实现
当处于设定的时间间隔内未发生新调用时,才会执行被调用的方法。
防抖(Debounce)的实现代码如下:
var debounce = function (func, threshold, execASAP) {
var timeout = null;
threshold = threshold || 100;
return function () {
var self = this;
var args = arguments;
var delayed = function () {
if (!execASAP) {
func.apply(self, args);
}
timeout = null;
};
if (timeout) {
clearTimeout(timeout);
} else if (execASAP) {
func.apply(self, args);
}
timeout = setTimeout(delayed, threshold);
};
}; 测试
测试用例与执行验证
测试代码示例如下:
var test = function (wrapper, threshold) {
var log = function () {
console.log(Date.now() - start);
};
var wrapperedFunc = wrapper(log, threshold);
var start = Date.now();
var arr = [];
for (var i = 0; i < 10; i++) {
arr.push(wrapperedFunc);
}
while(i > 0) {
var random = Math.random() * 1000;
console.log('index: ' + i);
console.log('random: ' + random);
setTimeout(arr[--i], random);
}
};
test(debounce, 1000);
test(throttle, 1000);