Increase the performance of a function that is executed many times in a short time

What is the debounce method and how to use it in Javascript

During the web development in the frontend area, we will be forced to increase the performance of a function, but one way or another sometimes, there are functions that cannot be modified or cannot be more optimized because they already accomplish a task.

However, but we can prevent it is carried out in every millisecond and force it to be executed just 1 time every X milliseconds and carry out the task once. Debounced functions do not execute when invoked, they wait for a pause of invocations over a configurable duration before executing, each new invocation restarts the timer.

For this we will use a debounce function which will help us with our mission, and is the following :

/**
* Execute a function given a delay time
* 
* @param {type} func
* @param {type} wait
* @param {type} immediate
* @returns {Function}
*/
var debounce = function (func, wait, immediate) {
     var timeout;
     return function() {
         var context = this, 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);
     };
};

In most of cases, this function will increase considerably the performance depending of the use, for example : 

1) On resizing event

If i need to resize many elements with javascript everytime the window is resized, that will mean extensive recurses consumption. Using debounce will make that the resize event will be trigger only 1 time according to the resize movement of the window.

$(window).resize(debounce(function(){
    // the following function will be executed every half second
    executeMyReallyHeavyTask();
},500)); // Milliseconds in which the task should be executed (500 = half second)

2) On keyup event

If you make your own autocomplete, you will need to  prevent that every time you press a button a call to the server be executed. Using debounce will make that only 1 Ajax call be executed on the press events.

$('#myInput').keyup(debounce(function(){
     // the following function will be executed every half second
     makeAjaxCall();
},500)); // Milliseconds in which the ajax call should be executed (500 = half second)

Debounce will increase the performance of your persistent execution functions in a short and elegant way.


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors