Skip to content

第 103 期(内功-性能):防抖 #106

@wingmeng

Description

@wingmeng

防抖和节流都是我们解决高频触发事件的两种常用解决方案,与节流不同,防抖是将若干次事件调用合成为一次,并在给定时间过去之后,或者连续事件完全触发完成之后,调用一次。

防抖函数:

function debounce(fn, delay) {
  var timer = null;
  delay = delay || 1000;

  return function() {
    var context = this;
    var args = arguments;
    
    clearTimeout(timer);
    timer = setTimeout(function() {
      fn.apply(context, args);
    }, delay);
  }
}

应用举例:

inputElm.addEventListener('input', debounce(function() {
  console.log(Date.now())
}));

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions