Skip to content

Latest commit

 

History

History
45 lines (36 loc) · 835 Bytes

防抖.md

File metadata and controls

45 lines (36 loc) · 835 Bytes

防抖

将多次执行变为最后一次执行

  1. immediate:
  2. true:立即执行
  3. false:延迟执行
  4. 返回值:immediate为true时返回执行结果
  5. 可以取消延迟

代码

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

  var debounced = function () {
    var context = this;
    var args = arguments

    if (timeout) clearTimeout(timeout)

    if (immediate) {
      var callNow = !timeout
      timeout = setTimeout(function(){
        timeout = null
      }, wait)

      if (callNow) result = func.apply(context, args)
    } else {
      timeout = setTimeout(function () {
        func.apply(context, args)
      }, wait)
    }

    return result
  }

  debounced.cancel = function () {
    clearTimeout(timeout)
    timeout = null
  }

  return debounced
}