throttle

JavaScript, Function

Creates a throttled function that only invokes the provided function at most once per every wait milliseconds

  • Use setTimeout() and clearTimeout() to throttle the given method, fn.
  • Use Function.prototype.apply() to apply the this context to the function and provide the necessary arguments.
  • Use Date.now() to keep track of the last time the throttled function was invoked.
  • Use a variable, inThrottle, to prevent a race condition between the first execution of fn and the next loop.
  • Omit the second argument, wait, to set the timeout at a default of 0 ms.
const throttle = (fn, wait) => {
  let inThrottle, lastFn, lastTime;
  return function() {
    const context = this,
      args = arguments;
    if (!inThrottle) {
      fn.apply(context, args);
      lastTime = Date.now();
      inThrottle = true;
    } else {
      clearTimeout(lastFn);
      lastFn = setTimeout(function() {
        if (Date.now() - lastTime >= wait) {
          fn.apply(context, args);
          lastTime = Date.now();
        }
      }, Math.max(wait - (Date.now() - lastTime), 0));
    }
  };
};
window.addEventListener(
  'resize',
  throttle(function(evt) {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
  }, 250)
); // Will log the window dimensions at most every 250ms

Recommended snippets

  • debouncePromise

    JavaScript, Function

    Creates a debounced function that returns a promise, but delays invoking the provided function until at least ms milliseconds have elapsed since the last time it was invoked. All promises returned during this time will return the same data.

  • debounce

    JavaScript, Function

    Creates a debounced function that delays invoking the provided function until at least ms milliseconds have elapsed since the last time it was invoked.

  • rearg

    JavaScript, Function

    Creates a function that invokes the provided function with its arguments arranged according to the specified indexes.