throttle example

by Yury

HTML

<body>
  <p>Move your mouse in this document</p>
  <div id="demo"></div>
</body>

CSS

* {
  background: #1e1e1e;
  font-family: sans-serif;
  color: #c0c0c0;
  text-align: center;
}
html, body { height: 100%;}
p {    
  margin: 0;
  padding: 10px 0;
}
#demo {
  width: 100%;
  height: 100%;
  border: 1px solid green;
}

JavaScript

function throttle(func, delay=500) {
  let timeout = null
  return function(...args) {
    if (!timeout) {
      timeout = setTimeout(() => {
        func.call(this, ...args)
        timeout = null
      }, delay)
    }
  }
}

document.body.addEventListener("mousemove", throttle(function(){
    document.getElementById("demo").innerHTML += "Hello World</br>";
},500));


/// another
export const throttle = (func, ms) => {
  let isThrottled = false;
  let savedArgs;
  let savedThis;

  function wrapper() {
    if (isThrottled) {
      savedArgs = arguments;
      savedThis = this;
      return;
    }

    func.apply(this, arguments);

    isThrottled = true;

    setTimeout(function () {
      isThrottled = false;
      if (savedArgs) {
        wrapper.apply(savedThis, savedArgs);
        savedArgs = savedThis = null;
      }
    }, ms);
  }

  return wrapper;
};