Tag Archives: UnderscoreJS

Performance optimization due to event limiting

Speed matters. Browser engines become faster and faster and nearly each month, there are new published benchmarks, to demonstrate the power of JavaScript. However, sometimes we have to reduce events, to keep good performance. Therefore I decided to introduce two very useful UnderscoreJS functions: throttle and debounce.

But in which cases do we have to reduce events? The common cases for limiting events, are user interactions.

  • Touch and mousemove events
  • Window resize event
  • The scroll event
  • Autocompletion while typing (keyup/keydown)

These events can be fired about hundred times per second (per event listener!). At each time, your code would be invoked and slows down your CPU performance. Furthermore the user can not recognize these fast operations, especially DOM manipulations.

Okay, let’s solve the problem and have a look at the differences between throttle and debounce.

Throttle breaks down your operation to a fix interval, which will be invoked as long the user performs the action. So, the operation won’t be called at each event, but in an defined interval.

Have a look at this simple example, to understand how the code works in production.

Using throttle is a good way to fix speed issues. In case of DOM manipulations, I personally prefer setting up throttle with 41 milliseconds, to get ~24 frames per second, which guarantees a fluent DOM animation.

Comparing to throttle, debounce helps you to identify the end of operations. This is useful, if you want to call any code, after the user entered any search term oder stopped resizing the window, etc.

Let’s see how to realize an auto-search:

Here you can find another short example, to see how it works.


These two functions give you a powerful tool to optimize slow JavaScript eventing issues. In case of window resize, it’s strongly recommended to evaluate CSS solutions, to solve the issue. Using CSS is always faster.