Tag Archives: throttle

Simple Throttle Function

When you’re handling events like window resize, keystrokes, mouse movement, and scrolling you need to be careful how many times you call heavy-handed functions. For instance, if you’re leveraging JavaScript to create responsive UIs in legacy browsers you probably don’t want to run complicated DOM-altering handlers 10 times a second when far fewer runs would be sufficient. Enter throttling.

Throttling is a means by which we can limit the number of times a function can be called in a given period. For instance, we may have a method that should be called no more than 5 times per second.

function callback () {

window.addEventListener("resize", throttle( callback, 200 ));

In the above, our throttle function takes a callback, and a rate limiter. It will fire the callback at most once every 200 milliseconds, or at most 5 times per second. So what does the actual implementation of the throttle function look like?

function throttle (callback, limit) {
    var wait = false;                 // Initially, we're not waiting
    return function () {              // We return a throttled function
        if (!wait) {                  // If we're not waiting
            callback.call();          // Execute users function
            wait = true;              // Prevent future invocations
            setTimeout(function () {  // After a period of time
                wait = false;         // And allow future invocations
            }, limit);

The above is fairly straight forward, but let’s discuss it briefly anyway.

The overall solution is to replace the user’s function with our own function. This allows us to add extra logic to the mix, such as how frequently the function can be invoked. This is why our throttle function inevitably returns a new function.

We manage our state with a variable called wait. When wait is true, our door is closed. When wait is false, our door is open. So by switching this value from true to false, we can allow the user’s function to be invoked. And by switching wait from false to true, we prevent any calls to the user function.

Anytime we switch this, we setup a timeout that will toggle it back to false after a period of time. This is where the 200 milliseconds comes in – we’re allowing the user to determine the length of time our door should be shut.

You should also use throttling for function that get called dozens, or hundreds of times. It’s rare that you actually want things to be called that often. The implementation in this post is fairly simple (I was shooting for conciseness), but more complicated solutions exist such as those in lo-dash, underscore, and more.

I created a fiddle with a throttled and and non-throttled callback. Tying this to the window resize event, I adjusted my window width/height briefly and let the number of calls speak for themselves:

Throttled results vs Non-throttled results

Throttled results vs Non-throttled results