绝妙的函数:重复触发防抖

Awesome Function: debounce

在线演示

利用闭包保存定时器的debounce函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 利用闭包保存定时器的debounce函数
const debounce1 = function () {
let timer = null
return function (fn, wait, scope) {
clearTimeout(timer)
timer = setTimeout(function () {
fn.call(scope)
}, wait)
}
}()

// 按钮触发事件
debounce1(() => {
paras[index - 1].innerHTML += ' 执行的内容'
}, 1000)

利用函数属性保存定时器的debounce函数

1
2
3
4
5
6
7
8
9
10
11
12
// 利用函数属性保存定时器的debounce函数
const debounce2 = function (fn, wait, scope) {
clearTimeout(debounce2.timer)
debounce2.timer = setTimeout(function(){
fn.call(scope)
}, wait)
}

// 按钮触发事件
debounce2(function () {
paras[index - 1].innerHTML += ' 执行的内容'
}, 1000)

可配置是否立即执行的debounce函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 可配置是否立即执行的debounce函数
const debounce3 = function () {
let timer = null
return function (fn, wait, scope, immediate) {
timer && clearTimeout(timer)
if (immediate) {
!timer && fn.call(scope)
timer = setTimeout(() => {
timer = null
count = 0
}, wait)
} else {
timer = setTimeout(function () {
fn.call(scope)
timer = null
}, wait)
}
}
}()

// 按钮触发事件,立即执行的内容
debounce3(function () {
paras[index - 1].innerHTML += ' 立即执行的内容'
}, 1000, null, true)

// 按钮触发事件,延迟执行的内容
debounce3(function () {
paras[index - 1].innerHTML += ' 延迟执行的内容'
}, 1000)