Home >Web Front-end >JS Tutorial >Debouncing in JS: Building better web apps
Have you ever been on a website, typed into a search bar, and noticed how the suggestions pop up in real-time without causing any lag? Or maybe you've filled out a form and seen the "Username already taken" message appear just as you're typing. Behind these seamless experiences is a powerful, often unsung hero of modern web development: debouncing.
Debouncing is a programming technique that ensures a function is executed only after a specified period of inactivity. Imagine you're typing into a search bar. Without debouncing, every keystroke would trigger a function call, potentially overwhelming the system with redundant requests. Debouncing solves this by waiting for a pause in your typing before executing the function, ensuring only one request is sent.
At its core its controlling the frequency of function execution. But for a easier understanding lets take an example of a door bell. Suppose there's a door beer that rings after 3 seconds of inactivity. After the initial ring if users tries to ring the bell as many times it won't ring unless he decides to pass another 3 seconds.
In JavaScript, debouncing is commonly used with event listeners like input, scroll, or resize. Here's a basic implementation:
function debounce(callback, delay) { let timeoutId; return (...args) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { callback(...args); }, delay); }; }
Lets understanding the different elements of this code:
function debounce(callback, delay) { let timeoutId; return (...args) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => { callback(...args); }, delay); }; }
const handleSearch = debounce((query) => { fetch(`https://api.example.com/search?q=${query}`) .then((response) => response.json()) .then((data) => console.log(data)); }, 500); document.getElementById("search").addEventListener("input", (e) => { handleSearch(e.target.value); });
.
.
.
.
.
Open to Suggestions
Have insights or additional tips on improving this blog? Feel free to share your feedback! Your input is invaluable for enhancing future content.
The above is the detailed content of Debouncing in JS: Building better web apps. For more information, please follow other related articles on the PHP Chinese website!