debounce方法

export function debounce(func, wait, immediate) {
  var timeout

  return function () {
    var context = this
    var args = arguments

    if (timeout) clearTimeout(timeout) // timeout是定时器ID,只有初始化状态下第一次触发的时候才不会执行;后续在周期内触发db函数会清除定时器,避免在周期内初始化timeout导致事件函数被执行
    if (immediate) {
      var callNow = !timeout
      timeout = setTimeout(function () {
        timeout = null // 如果周期内db函数未触发,则重新初始化timeout
      }, wait)
      if (callNow) func.apply(context, args) // 初始化状态下,立即执行事件函数
    } else {
      timeout = setTimeout(function () {
        // 在周期内db函数被触发会更新定时器,延迟事件函数的执行
        func.apply(context, args)
      }, wait)
    }
  }
}

  

posted @ 2024-11-22 10:09  心意12  阅读(21)  评论(0)    收藏  举报