Debouncing in JavaScript
Ever noticed how a search box or resize event can trigger a function dozens of times per second (𝐞.𝐠 𝐟𝐥𝐢𝐩𝐤𝐚𝐫𝐭 𝐬𝐞𝐚𝐫𝐜𝐡𝐛𝐨𝐱)?
Calling APIs or heavy logic on every keystroke is inefficient and costly.
That’s where Debouncing comes in 👇
Debouncing is a common JavaScript technique used to control how often a function executes. Instead of running a function every time an event fires, debouncing ensures it runs only after the event stops firing for a certain period.
This article focuses on how debouncing is implemented, step by step.
𝐃𝐞𝐛𝐨𝐮𝐧𝐜𝐢𝐧𝐠 𝐞𝐧𝐬𝐮𝐫𝐞𝐬 𝐚 𝐟𝐮𝐧𝐜𝐭𝐢𝐨𝐧 𝐞𝐱𝐞𝐜𝐮𝐭𝐞𝐬 𝐨𝐧𝐥𝐲 𝐚𝐟𝐭𝐞𝐫 𝐚 𝐜𝐞𝐫𝐭𝐚𝐢𝐧 𝐝𝐞𝐥𝐚𝐲 𝐡𝐚𝐬 𝐩𝐚𝐬𝐬𝐞𝐝 𝐬𝐢𝐧𝐜𝐞 𝐭𝐡𝐞 𝐥𝐚𝐬𝐭 𝐞𝐯𝐞𝐧𝐭.
The Core Idea Behind Debouncing-
At its core, debouncing relies on three concepts:
Each new call cancels the previous scheduled execution and schedules a new one.
If the event keeps firing, the previous execution is cancelled - only the final one runs.
Debounce Implementation-
function debounce(fn, delay) {
let timerId;
return function (...args) {
const context = this;
// capture the current calling context to preserve `this` inside fn
clearTimeout(timerId);
timerId = setTimeout(() => {
fn.apply(context, args); // apply invokes the original function with the same `this` context and forwards all arguments correctly
}, delay);
};
}
function fetchData(query, method) {
console.log("Fetching Data for", query, "method=", method, "...");
}
const debouncedFetch = debounce(fetchData, 300);
const inputField = document.getElementById("search-input");
inputField.addEventListener("input", function (e) {
debouncedFetch(e.target.value, Date.now());
});
𝐖𝐡𝐲 𝐢𝐭 𝐦𝐚𝐭𝐭𝐞𝐫𝐬:
💡 𝐂𝐨𝐦𝐦𝐨𝐧 𝐮𝐬𝐞 𝐜𝐚𝐬𝐞𝐬:
𝑰𝒏 𝒔𝒉𝒐𝒓𝒕: 𝑫𝒆𝒃𝒐𝒖𝒏𝒄𝒊𝒏𝒈 𝒅𝒐𝒆𝒔𝒏’𝒕 𝒄𝒉𝒂𝒏𝒈𝒆 𝒘𝒉𝒂𝒕 𝒂 𝒇𝒖𝒏𝒄𝒕𝒊𝒐𝒏 𝒅𝒐𝒆𝒔 - 𝒊𝒕 𝒄𝒉𝒂𝒏𝒈𝒆𝒔 𝒘𝒉𝒆𝒏 𝒊𝒕 𝒓𝒖𝒏𝒔.