What is debounce in Javascript?

Hi, debounce in Javascript is a code technique that we can use to improve our applications performance.

Let see the next example:

// Gettin the input DOM by the id
let search = document.getElementById('search');
let counter = 1;

// Event listener - listen when "keyup" event happend
search.addEventListener('keyup', function() {
    // 1 execute this "betterFunction"

// Function that simulate petitions to the server
let getData = () => {
    console.log('counter--->', counter++)

// Debounce function
function debounce(fn, delay) { // callback function
    let timer;

    return function() { // closure function

        let context = this; // Holding the current context

        clearTimeout(timer); // Cleanning the timer

        // Set timout that
        timer = setTimeout(() => {
            // after 300 milliseconds the getData function will be executed
            fn.apply(context, arguments); // Appling the current context and arguments to getData function
        }, delay); // after 300 milliseconds execute the code inside the arrow function

// performanceFunction have by reference the "debounce" function
const performanceFunction = debounce(getData, 300);


This means that we are going to insert a delay (time) and after that time pass then the getData (petition to the server) will be executed, and in that way we can control the numbers of petitions that we make to the server all of this is “debouncing” and this is a good practice to have a better performance in our web applications.

By Cristina Rojas.