Events such as window resize, mouse events, key stroke events, DOM manipulation, etc… take more memory and CPU time. Calling such heavy events continuously might cause the browser to hang or crash. In such cases the functions can be throttled, that is the number of times the functions are called for a given period can be limited. For example, we can limit a method call to trigger not more than once per second.

In the example below, the event handler function for resize event is throttled in such a way that it is called only once for every two seconds. Even if windows are resized continuously, the handler is called once the setTimeout timer expires after 2000ms. If there is a timer already running, it is cleared using clearTimeout. The context of handler is saved and the handler function resizeCount() is called within the context. The handler is executed after the timer expires.

Example if function throttling in JavaScript

 

›› go to examples ››