Skip to content

debounce/throttle #5

@homobulla

Description

@homobulla

debounce(防抖)和throttle(节流)是为了阻止用户高频率的执行某些复杂操作。比如表单提交、点击事件、输入框等等一系列场景。

debounce
原理就是推迟用户操作的真正触发事件时间在限定时间内没有再次操作时进行真正的触发。
其中,推迟时间是以事件最后一次触发为准。

function debounce(fn, delay) {
  var ctx;
  var args;
  var timer = null;

  var later = function () {
    fn.apply(ctx, args);
    // 当事件真正执行后,清空定时器
    timer = null;
  };

  return function () {
    ctx = this;
    args = arguments;
    // 当持续触发事件时,若发现事件触发的定时器已设置时,则清除之前的定时器
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    // 重新设置事件触发的定时器
    timer = setTimeout(later, delay);
  };
}

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