Growing with the Web

Performing heavy actions on events that fire frequently

Published
Tags:

This snippet is useful when applied to events that occur many times such as resize and scroll, particularly when the callback does heavy processing. It throttles the calls to the callback by only calling in to the callback if the event has not occurred again in the last 300ms. This technique is called ‘debouncing’.

Snippet

var addDelayedListener = function (eventName, callback, delay) {
  var timeout;
  delay = delay || 300;
  window.addEventListener(eventName, function () {
    window.clearTimeout(timeout);
    timeout = window.setTimeout(callback, delay);
  });
};

Usage

addDelayedListener('resize', function () {
  alert('Resized');
});

// Custom delay
addDelayedListener('scroll', function () {
  alert('scroll');
}, 400);

Comments

comments powered by Disqus
Like this article?
Subscribe for more!