• 0

Implement a debounce function in javascript

Problem description :

Implement a debounce function. For example, you wanted the mousmove function to be called only after 2 seconds has passed between mouse move events.

A debounce function limits the rate at which a function can fire.


Approach 1 : Implement a debounce function without immediate parameter

Solution :


Demo Notes:

In this demo, I will demonstrate the difference between attaching a normal vs debounced event handler to the mousemove event.

To see the effect of the normal event handler, use the following lines in the JavaScript file. (Default) - This will limit the execution of the event handler function once per 2 seconds.

// movearea.addEventListener('mousemove', eventHandler);
movearea.addEventListener('mousemove', debounce(eventHandler, 2000));

To see the effect of the debounced event handler, use the following lines in the JavaScript file. - This will execute the event handler function every time it is called.

movearea.addEventListener('mousemove', eventHandler);
// movearea.addEventListener('mousemove', debounce(eventHandler, 2000));

Demo without Immediate parameter :

[codepen_embed height="268" theme_id="0" slug_hash="VevMRY" default_tab="result" user="kavitshah8"]See the Pen Debounce by Kavit Shah (@kavitshah8) on CodePen.[/codepen_embed]

Approach 2 : Implement a debounce function with immediate parameter

Solution :


Demo notes:

  • Refer the demo notes in the approach 1.

Demo without Immediate parameter :

[codepen_embed height="268" theme_id="0" slug_hash="EPVLrw" default_tab="result" user="kavitshah8"]See the Pen Debounce with Immediate by Kavit Shah (@kavitshah8) on CodePen.[/codepen_embed]