Skip to content

Commit d81be2f

Browse files
skimklinYuChengKai
authored andcommitted
修改: 新增防抖函数中清除定时器的条件分支,防止创建多个定时器
1 parent 430e541 commit d81be2f

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

JS/JS-ch.md

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -800,7 +800,13 @@ _.debounce = function(func, wait, immediate) {
800800
// 如果定时器不存在且立即执行函数
801801
var callNow = immediate && !timeout;
802802
// 如果定时器不存在就创建一个
803-
if (!timeout) timeout = setTimeout(later, wait);
803+
// 定时器存在则清除当前定时器并重新设定一个新的定时器
804+
if (!timeout) {
805+
timeout = setTimeout(later, wait);
806+
} else {
807+
clearTimeout(timeout);
808+
timeout = setTimeout(later, wait);
809+
}
804810
if (callNow) {
805811
// 如果需要立即执行函数的话 通过 apply 执行
806812
result = func.apply(context, args);

0 commit comments

Comments
 (0)