Skip to content

debounce

  • 基础版
js
export function debounce(fn, wait) {
  let timer
  return function (...args) {
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.call(this, ...args)
    }, wait)
  }
}

鼠标放下去试试, 每隔 1 秒数字加 1

0
  • 立刻执行 首次会立刻执行, 之后连续触发不会执行,停止触发 N 秒后才执行
js
export function debounce(fn, wait, immediate) {
  let timer
  return function (...args) {
    clearTimeout(timer)
    if (immediate && !timer) {
      fn.apply(this, args)
    }
    timer = setTimeout(function () {
      fn.apply(this, args)
    }, wait)
  }
}

鼠标放下去试试, 每隔 1 秒数字加 1

0
  • 立刻执行, 首次会立刻执行, 之后连续触发不执行, 停止触发 N 秒后也不会执行
js
export function debounce(fn, wait, immediate) {
  let timer
  return function (...args) {
    clearTimeout(timer)
    if (immediate) {
      let callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, wait)
      if (callNow) fn.apply(this, args)
    } else {
      timer = setTimeout(function () {
        fn.apply(this, args)
      }, wait)
    }
  }
}

鼠标放下去试试, 每隔 1 秒数字加 1

0