OPY-bbt / OPY-bbt.github.io

my webpage
https://opy-bbt.github.io/
0 stars 0 forks source link

throttle debounce #5

Open OPY-bbt opened 5 years ago

OPY-bbt commented 5 years ago

两者区别

对于连续触发的事件,防抖只是执行一次,节流是执行多次

OPY-bbt commented 5 years ago
   function log(content) {
      console.log(content);
    }

    function debounce(fn) {
      let timer = null;

      return function() {
        if (timer) window.clearTimeout(timer);
        timer = setTimeout(() => {
          fn.apply(this, arguments);
        }, 1000);
      }
    }

    function throttle(fn) {
      let canRun = true;

      return function() {
        if (!canRun) return;
        canRun = false;
        window.setTimeout(() => {
          fn.apply(this, arguments);
          canRun = true;
        }, 1000)
      }
    }

    const debounceLog = debounce(log);
    const throttleLog = throttle(log);

    let count = 0
    let timer = window.setInterval(() => {
      debounceLog('debounce log');
      throttleLog('throttle log');
      count++;
      if (count === 20) {
        clearInterval(timer);
      }
    }, 200);