Let’s say you’re working on a webpage. You want something on that webpage to respond to changing the size of the window, in a way that can’t be handled with straight CSS or media queries. So you take advantage of the window resize event, attach an event handler to do your thing, and all seems to be good.

However, directly hooking into window.onresize isn’t very performant. Each small change made to the window size will fire a separate resize event. If you’re performing an expensive operation each resize, your page will start to lag and the user experience will suffer. At the very least, it may be confusing or unnecessary to react to every little change.

Luckily there are two ways to improve the performance of window.onresize: throttling and debouncing.

No Optimization

Here’s a contrived example with no optimization. Try resizing the window; every small change in the window size triggers the event handler.

See the Pen Regular window.resize Example by Ben Centra (@bencentra) on CodePen.


Throttling

Throttling window.onresize limits how often the event handler will be called by setting a timeout between calls. This will allow you to call the function at a reasonable rate.

A basic example looks like this:

See the Pen Throttling Example by Ben Centra (@bencentra) on CodePen.


Debouncing

Debouncing window.onresize will only call the event handler after the event has stopped firing for a certain amount of time. This will ensure that your function will only be called once the resizing is “complete.”

A basic example looks like this:

See the Pen Debouncing Example by Ben Centra (@bencentra) on CodePen.


Throttling and debouncing can be applied to other JavaScript events as well. If you don’t want to implement them yourself, several libraries have implementations and many plugins already exist.