JavaScript 节流与防抖函数实现及测试详解
作者:木棉时间:2026-10-27 08:30:02浏览:401
本文深入解析 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);作者最新文章
JS中将数组和对象混合组装为JSON字符串
2026-11-05 16:41:42
JS运算符优先级与结合性的区别是什么?
2026-11-05 13:22:02
JS Map怎么只遍历Key或Value
2026-11-05 13:00:36
D3.js 与 ECharts 选型对比:灵活性 vs 开发效率
2026-11-05 09:45:01
为什么JS中typeof []返回object:数组类型检测误区解析
2026-11-04 19:50:47
