防抖函数封装 取消 立即执行

// 代码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))
posted @ 2022-03-03 18:04  有肌肉的小眼睛  阅读(67)  评论(0编辑  收藏  举报