防抖函式封裝 取消 立即執行
阿新 • • 發佈:2022-03-03
// 程式碼2
const debounce = (func, wait = 0) => {
let timeout = null
let args
function debounced (...arg) {
args = arg
if (timeout) {
clearTimeout(timeout)
timeout = null
}
// 以Promise的形式返回函式執行結果
return new Promise((res, rej) => {
timeout = setTimeout(async () => {
try {
const result = await func.apply(this, args)
res(result)
} catch (e) {
rej(e)
}
}, wait)
})
}
// 允許取消
function cancel () {
clearTimeout(timeout)
timeout = null
}
// 允許立即執行
function flush () {
cancel()
return func.apply(this, args)
}
debounced.cancel = cancel
debounced.flush = flush
return debounced
}
//測試程式碼
const ipt = document.querySelector('input')
ipt.addEventListener('input', debounce(e => {
search(e.target.value).then(resp => {
}, e => {
})
}, 500))