Performance optimization is crucial in JavaScript applications, especially when handling frequent user interactions like scrolling, resizing, or keypress events. Two powerful techniques used to limit function execution frequency are debouncing and throttling.
In this blog, we’ll explain what debouncing and throttling are, provide detailed coding examples, and cover interview questions with answers related to these concepts.
What is Debouncing in JavaScript?
Debouncing is a technique that ensures a function is executed only after a specified delay following the last event trigger. It is useful for situations where multiple rapid event triggers should result in a single function execution after a delay.
Common Use Cases of Debouncing
- Search box auto-suggestions (trigger API call after user stops typing)
- Resize event handlers (execute code after user stops resizing window)
- Button click prevention (prevent multiple clicks from submitting a form multiple times)
Example: Implementing Debouncing
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
// Example usage
function searchQuery(query) {
console.log("Fetching results for:", query);
}
const debouncedSearch = debounce(searchQuery, 300);
// Simulating user typing in a search box
debouncedSearch("Ja");
debouncedSearch("Jav");
debouncedSearch("Java"); // Only "Java" triggers the searchQuery function after 300ms
How It Works
- Every time
debouncedSearch
is called, the previous timer is cleared. - Only the final call (after delay) executes the
searchQuery
function.
What is Throttling in JavaScript?
Throttling ensures that a function is executed at most once within a specified time interval, even if triggered multiple times.
Common Use Cases of Throttling
- Scroll event handling (trigger an action once per interval during scrolling)
- API polling (limit API requests at regular intervals)
- Button click handling (prevent multiple rapid clicks from triggering multiple submissions)
Example: Implementing Throttling
function throttle(func, limit) {
let lastFunc;
let lastTime = 0;
return function (...args) {
const now = Date.now();
if (now - lastTime >= limit) {
func.apply(this, args);
lastTime = now;
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
func.apply(this, args);
lastTime = now;
}, limit - (now - lastTime));
}
};
}
// Example usage
function onScroll() {
console.log("Scrolling event triggered:", Date.now());
}
const throttledScroll = throttle(onScroll, 1000);
// Simulating multiple scroll events
window.addEventListener("scroll", throttledScroll);
How It Works
- The function executes immediately when first called.
- After that, it executes only once per specified interval (1s in this case).
Debouncing vs. Throttling: Key Differences
Feature | Debouncing | Throttling |
---|---|---|
Execution Time | Delays execution until after event stops | Executes at fixed intervals |
Best Use Cases | Search input, resizing events | Scrolling, button clicks, API polling |
Number of Executions | 1 (after delay) | Multiple (at regular intervals) |
Interview Questions on Debouncing and Throttling
1. What is the difference between debouncing and throttling?
Answer:
- Debouncing postpones function execution until after a specified delay following the last event trigger.
- Throttling executes a function at most once per interval, even if the event keeps triggering.
2. When would you use debouncing over throttling?
Answer:
Use debouncing when you want to ensure execution happens only after the event has stopped firing. Example: search input auto-suggestions.
3. How would you implement a debounce function in JavaScript?
Answer:
The following function delays execution until after the event stops occurring for the specified time.
function debounce(func, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => func.apply(this, args), delay);
};
}
4. How would you implement a throttle function in JavaScript?
Answer:
The following function ensures that execution happens at most once in the given time frame.
function throttle(func, limit) {
let lastFunc;
let lastTime = 0;
return function (...args) {
const now = Date.now();
if (now - lastTime >= limit) {
func.apply(this, args);
lastTime = now;
} else {
clearTimeout(lastFunc);
lastFunc = setTimeout(() => {
func.apply(this, args);
lastTime = now;
}, limit - (now - lastTime));
}
};
}
5. Can you use both debouncing and throttling together?
Answer:
Yes! You can apply debouncing inside throttling to ensure that an event fires at regular intervals while also handling spikes in event triggers efficiently.
Final Thoughts
- Debouncing is best when you want to delay execution until the event has stopped firing (e.g., search input).
- Throttling is best when you want execution to happen at fixed intervals (e.g., scrolling events).
- Both techniques help optimize performance and reduce unnecessary function calls.
Additional Essential JavaScript Interview Questions on Various Topics
- Master JavaScript Modules vs. CommonJS: The Ultimate 2024 Guide
- Ultimate Guide to Mastering JavaScript Symbols, Scope, and Immutability in 2024
- Mastering SOLID Principles in JavaScript: A Guide with Code Examples 2024
- Mastering Design Patterns for Frontend Developers: A Comprehensive Guide
- Understanding JavaScript Closures: A Comprehensive Guide
- JavaScript Event Loop: A Deep Dive with Examples 2024
- Web Workers: Empowering Frontend Development with This Ultimate Guide 2024
- Service Workers: Enhancing JavaScript Performance with This Definitive Guide 2024
- Arrow Functions vs. Normal Functions in JavaScript 2024
- Understanding call, bind, and apply in JavaScript 2024
- Web Security Essentials: Protecting Against CSRF, XSS, and Other Threats 2024
- Frontend Security: Best Practices for Authentication and Authorization 2024
- localStorage vs sessionStorage: The Ultimate Guide to Mastering Web Storage in JavaScript for 2024
- Variable Scopes Demystified: The Ultimate Beginner’s Guide to JavaScript 2024
- Javascript
React Js Interview questions:
- Mastering React Server-Side Rendering (SSR): A Deep Dive into SSR, CSR, and SSG
- Code Splitting and Lazy Loading in React: Boost Performance in Large Applications
- Higher-Order Components (HOC): Are They Still Relevant in 2024?
Mastering the useReducer Hook in React 2024: The Ultimate Guide for Advanced State Management - How Does React’s Context API Work? When Would You Use It Instead of a State Management Library Like Redux?
- Mastering React Hooks: The Ultimate 2024 Guide with Detailed Examples
- Virtual DOM: How Does React’s Reconciliation Algorithm Work?
- useEffect Hook in React: In-Depth Explanation and Performance Optimization
Top Javascript Books to Read
- You Don`t Know JS: 6 Volume Set (Greyscale Indian Edition) Paperback – 1 January 2017– by Kyle Simpson (Author)
- JavaScript: The Definitive Guide: Master the World’s Most-Used Programming Language, 7th Edition (Greyscale Indian Edition) [Paperback] David Flanagan – by David Flanagan | 11 July 2020
- JavaScript and HTML5 Now Kindle Edition– by Kyle Simpson
- Coding with Javascript for Dummies– by Chris Minnick and Eva Holland | 1 January 2015
- JavaScript from Beginner to Professional: Learn JavaScript quickly by building fun, interactive, and dynamic web apps, games, and pages-by Laurence Lars Svekis, Maaike Van Putten, et al. | 15 December 2021
- Head First JavaScript Programming: A Brain-Friendly Guide [Paperback] Robson, Elisabeth and Freeman, Eric– by Elisabeth Robson and Eric Freeman | 1 January 2014