Categories
Uncategorized

Throttling (ES6)

Sometimes, we need to limit the number of method calls based on time. A throttling method is the way to go.

Code

const throttle = (fn, delay) => {
  let timeout = false;
  return (...rest) => {
    if (!timeout) {
      timeout = true;
      fn.apply(this, rest);
      setTimeout(() => {
        timeout = false;
      }, delay);
    }
  }
}


const logger = (inp) => console.log(inp);

const throttledMethod = throttle(logger, 1000);

const button = document.createElement('button');
document.body.appendChild(button);
button.addEventListener('click', () => throttledMethod('Hello World!'));

Demo