Advertisement
Debouncing is a programming technique used to limit how often a function is executed. Specifically, it ensures that a function is only triggered after a certain amount of time has passed since it was last invoked. This prevents unnecessary or excessive function calls, which can help optimize performance and reduce unnecessary CPU usage or API requests.
For example, when a user types in a search box, you typically want to wait until they’ve finished typing before fetching suggestions. Without debouncing, an API call would be triggered on every keystroke, potentially causing performance issues. With debouncing, the function call is postponed until the user stops typing for a specified period (e.g., 300ms). If the user types again before this time elapses, the timer resets.
Typical use cases for debouncing include:
* Search box suggestions (wait until typing pauses before fetching results)
* Auto-saving text fields (save only after the user stops typing)
* Preventing double-clicks on buttons
* Handling window resize or scroll events efficiently
Example Debounce Function:
JavaScript
1function debounce(func, timeout = 500) {
2
3let timer;
4
5return function (...args) {
6 clearTimeout(timer);
7 timer = setTimeout(() => {
8 func.apply(this, args);
9 }, timeout);
10};
11}Usage Example:
JavaScript
1function fetchResults() {
2
3console.log("Fetching input suggestions");
4}
5
6const processChange = debounce(fetchResults, 300);
7
8// Attach to input element
9<input type="text" onkeyup="processChange()" />
10
11// Attach to button
12<button onclick="processChange()">Click me</button>
13
14// Attach to window event
15
16window.addEventListener("scroll", processChange);How it works:
When processChange is invoked (e.g., by typing or clicking), any pending execution is canceled, and the function is scheduled to run after the specified delay. If another event occurs before the delay is up, the timer resets, and the function will only run after events have stopped for the delay duration.
Debouncing is an essential tool for improving user experience and application performance, especially when dealing with events that can fire rapidly and repeatedly.
Advertisement
JavaScript Coding Exercise 8
Test your knowledge with this interactive coding challenge.
Start CodingAdvertisement