JavaScript LogoWhen an event such as window.resize() runs more often than you want it to, you can control how many times your event handler runs.

Sometimes events fire very quickly and more often than you would like; window.resize is a perfect example. It’s quite common to assign an event handler that will run every time the user resizes the browser. Unfortunately, however, there is no “resize-end” event. The resize event will fire for every change in pixel. This means that if the user resizes the window 100px, that resize event will run 100 times. But what you usually want is for that event handler to run when the user has finished resizing the window. Since there is no “resize-end” event, we have to use a timeout to imitate the kind of behavior we want.

Example # 1

In Example # 1, we have assigned an anonymous function to the onresize event of the window object. Unfortunately, though, the unordered list is updated every time the window size changes by one pixel. What we want is for the update message to appear after the user has finished resizing the window.

Click here to see the code for Example # 1 in action: http://jsfiddle.net/zWQ8D/

Example # 2

Click here to see the code for Example # 2 in action: http://jsfiddle.net/zWQ8D/1/

In Example # 2, we have created a function named “throttle”. This function will set a timeout of whatever numeric value is passed in as an argument. But every time that same function is called, the timeout, which exists in the global scope, is cleared and reset. Because our window.onresize event calls this function many times in rapid succession, the timeout is constantly re-set, which means that the function passed-in never executes.

The magic happens after the user has stopped resizing the window. Since every call to the “throttle” function sets a timeout, once 250 milliseconds has passed since the last call to the function, the final timeout actually executes. The net result is that the event handler for the window.resize event “feels” as if it only executes once the user has finished resizing the window. What actually happens is that the event handler is passed to the “throttle” function over and over in rapid succession, but our “throttle” function ensures that it only executes if 250 milliseconds has passed since the last time it was called.