Ask any question about JavaScript here... and get an instant response.
Post this Question & Answer:
How can I debounce a JavaScript function triggered by a scroll event?
Asked on Apr 03, 2026
Answer
Debouncing a function ensures that it only executes after a specified delay period has passed since the last time it was invoked. This is particularly useful for optimizing performance in events like scrolling. Below is an example of how to debounce a function triggered by a scroll event.
<!-- BEGIN COPY / PASTE -->
function debounce(func, wait) {
let timeout;
return function(...args) {
const context = this;
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(context, args), wait);
};
}
function handleScroll() {
console.log("Scroll event triggered!");
}
const debouncedScroll = debounce(handleScroll, 200);
window.addEventListener("scroll", debouncedScroll);
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "debounce" function takes two arguments: the function to debounce and the wait time in milliseconds.
- The "handleScroll" function is the actual function that will be called when the scroll event is triggered.
- "debouncedScroll" is the debounced version of "handleScroll", which will only execute after 200 milliseconds have passed since the last scroll event.
- The "window.addEventListener" method attaches the debounced function to the scroll event.
Recommended Links:
