Pearl Apps Blog
Jan 22, 2022

How to use the debounce function in JavaScript

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.

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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);

  };

};

Run

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.

1

2

3

4

5

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.

Pearl App

Pearl App

Pearl Apps Terms and conditions / Privacy Policy

Leave a Reply

Related Posts

Categories