debounce 和 throttle

144 阅读1分钟
myDebounce = (fn, wait) => {
    let timeout = null;
    return () => {
      if (timeout) {
        clearTimeout(timeout);
      }
      timeout = setTimeout(fn, wait);
    }
}

mythrottle = (fn, delay) => {
    let valid = true
    return function () {
      if (!valid) {
        return;
      }
      valid = false
      setTimeout(() => {
        fn();
        valid = true;
      }, delay)
    }
}

test = () => {
    console.log('test');
}

document.body.addEventListener('scroll', this.myDebounce(this.test, 1000));
document.body.addEventListener('scroll', this.mythrottle(this.test, 1000));