Mitigate Click-rage With Debounce in Web Application.

In web development, efficiency and user experience is king. One powerful technique in achieving both is the use of debounce.

Why is Debounce important?

I stumbled upon a button in a web application that executed a rather time consuming function. As it turned out, developer hadn’t implemented any debouncing or throttling.

Of course I had to test it.

This lead to excessive load on the server and a decrease the application’s performance.
You don’t want that!

Implementing Debounce in JavaScript.

Simple way to implement Debounce in JavaScript:

// Stefan Sommarsjö
// https://github.com/sestsom/Web

let debounceTimeout;

function debounceFunction(func, delay) {
    clearTimeout(debounceTimeout);
    debounceTimeout = setTimeout(func, delay);
}

function buttonClicked() {
    document.getElementById("status").textContent = "Function Executed!";
    // Reset after 2 seconds
    setTimeout(() => {
        document.getElementById("status").textContent = "Ready...";
    }, 2000);
}

document.getElementById("actionButton").addEventListener("click", () => {
    debounceFunction(buttonClicked, 1000); // Milliseconds debounce time
});

The debounce function can be wrapped around any event handler or function that you want to control.

https://github.com/sestsom/Web

Leave a comment