Skip to content

防抖和节流啥区别,实现一个防抖和节流 #14

@NsNe

Description

@NsNe

防抖

在一定时间内执行一次,如果在此时间内再次触发,则重新计时

const debounce = (func, timeout, immediate = false) => {
  let timer = null;
  return function (...args) {
    if (!timer && immediate) {
      func.apply(this, args);
    }
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      func.apply(this, args);
    }, timeout);
  }
}

节流

在一定时间内执行一次,如果在此时间内再次触发,则会拦截不执行

const throttle = (func, timeout) => {
  let timer = null;
  return function (...args) {
    if (!timer) {
      timer = setTimeout(() => {
        timer = null;
        func.apply(this, args);
      }, timeout);
    }
  }
}

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