Awesome Function: debounce
在線演示
利用閉包保存定時(shí)器的debounce函數(shù)
// 利用閉包保存定時(shí)器的debounce函數(shù)
const debounce1 = function () {
let timer = null
return function (fn, wait, scope) {
clearTimeout(timer)
timer = setTimeout(function () {
fn.call(scope)
}, wait)
}
}()
// 按鈕觸發(fā)事件
debounce1(() => {
paras[index - 1].innerHTML += ' 執(zhí)行的內(nèi)容'
}, 1000)
利用函數(shù)屬性保存定時(shí)器的debounce函數(shù)
// 利用函數(shù)屬性保存定時(shí)器的debounce函數(shù)
const debounce2 = function (fn, wait, scope) {
clearTimeout(debounce2.timer)
debounce2.timer = setTimeout(function(){
fn.call(scope)
}, wait)
}
// 按鈕觸發(fā)事件
debounce2(function () {
paras[index - 1].innerHTML += ' 執(zhí)行的內(nèi)容'
}, 1000)
可配置是否立即執(zhí)行的debounce函數(shù)
// 可配置是否立即執(zhí)行的debounce函數(shù)
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)
}
}
}()
// 按鈕觸發(fā)事件,立即執(zhí)行的內(nèi)容
debounce3(function () {
paras[index - 1].innerHTML += ' 立即執(zhí)行的內(nèi)容'
}, 1000, null, true)
// 按鈕觸發(fā)事件盈咳,延遲執(zhí)行的內(nèi)容
debounce3(function () {
paras[index - 1].innerHTML += ' 延遲執(zhí)行的內(nèi)容'
}, 1000)
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者