Throttling events with setTimeout

May 20, 2016

Time and time again, we need to listen for an event (scroll, keyup) and execute some arbitrary code when that event fires. If you do this enough, you’ll likely run into a situation where you are just receiving way too many events. In these cases, it’s best to set and clear a timeout to make sure your code only fires once in a while.


Say you want to run some advertising code on the scroll event, to track and see if any of your ads have scrolled into or out of view. You might have something like this:

window.addEventListener('scroll', function() {
  // Check to see what ads are showing!
}, false);

This will work, but you’ll likely be executing that code thousands of times as the user scrolls around the screen. Another example would be wanted to do an AJAX call as the user types into a form field to popular some search suggestions. Maybe you have:

window.addEventListener('keyup', function() {
  // $.GET some sweet suggestions!
}, false);

But again, you end up triggering hundreds of AJAX calls as the user types, deletes, re-types. So what’s the solution?

setTimeout and clearTimeout

Most of you have probably used setTimeout before, you can execute some code after a specified delay. Something like this:

window.setTimeout(function() {
  alert("Hello World!");
}, 2000);

That’s part of the equation, if inside our event listener we put a timeout, it wouldn’t ever fire right away. It would, however, still fire just as many times as before. Just now they’d all be delayed by 200 milliseconds. Here’s where we can use window.clearTimeout to effectively throttle our event listeners.

var timedEvent;

window.addEventListener('scroll', function() {

  timedEvent = setTimeout(function() {
    // AJAX or Check for ads
  }, 2000);
}, false);

And there you have it! Change that 2000 value to whatever frequency you’d like to run your code.