Trusted answers to developer questions
Trusted Answers to Developer Questions

RELATED TAGS

How to use the debounce function in JavaScript

Educative Answers Team

The debounce() function forces a function to wait a certain amount of time before running again. The function is built to limit the number of times a function is called.

svg viewer
The Send Request() function is debounced. Requests are sent only after fixed time intervals regardless of how many times the user presses the button.

Events such as scrolling, mouse movement, and keypress bring great overhead with them if they are captured every single time they fire. The function aims to reduce overhead by preventing a function from being called several times in succession.

Implementation

The following implementation of debounce returns a function that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. If immediate is passed as an argument to the function, the function triggers immediately and then waits for the interval before being called again.

function debounce(func, wait, immediate) {
  var timeout;

  return function executedFunction() {
    var context = this;
    var args = arguments;
	    
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };

    var callNow = immediate && !timeout;
	
    clearTimeout(timeout);

    timeout = setTimeout(later, wait);
	
    if (callNow) func.apply(context, args);
  };
};

On passing a function and a time interval to debounce, a function is returned that can be passed on to the event listeners that execute​ the function.

var returnedFunction = debounce(function() {
    // The function's code
}, 250);

window.addEventListener('resize', returnedFunction);

Code

The following example displays an alert box 2 seconds after the user has stopped pressing the button. It passes the debounced function to the button’s onClick event handler.

RELATED TAGS

Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.

soc2