What is the difference between Lodash's debounce and throttle? What scenarios are they suitable for?
Lodash's debounce and throttle are two very important performance optimization functions used to control the execution frequency of functions. Here is a detailed answer:
Debounce
What is Debounce?
Debounce means delaying the execution of a function after an event is triggered. If the event is triggered again during this delay period, the timer restarts. The function only executes after the event stops triggering and the specified delay time has passed.
Debounce Use Cases
- Search input: Send search request only after user stops typing
- Window resize: Recalculate layout only after resizing stops
- Form validation: Validate only after user stops typing
- Button clicks: Prevent rapid multiple clicks
Debounce Implementation Principle
javascript// Simple debounce implementation function debounce(func, wait) { let timeout; return function() { const context = this; const args = arguments; clearTimeout(timeout); timeout = setTimeout(() => { func.apply(context, args); }, wait); }; } // Usage example const debouncedSearch = debounce(function(keyword) { console.log('Search:', keyword); }, 300); // Fast input, only executes once after stopping input for 300ms debouncedSearch('a'); debouncedSearch('ab'); debouncedSearch('abc');
Using Lodash Debounce
javascriptimport _ from 'lodash'; // Basic usage const debouncedFn = _.debounce(function() { console.log('Executed'); }, 300); // Immediate execution option const debouncedImmediate = _.debounce(function() { console.log('Immediate execution'); }, 300, { leading: true, trailing: false }); // Cancel debounce const debounced = _.debounce(function() { console.log('Execute'); }, 300); debounced(); debounced.cancel(); // Cancel execution
Throttle
What is Throttle?
Throttle means that within a specified time interval, the function executes at most once. No matter how many times the event is triggered, the function executes at a fixed time interval.
Throttle Use Cases
- Scroll events: Trigger at fixed frequency while scrolling
- Mouse movement: Limit mousemove event trigger frequency
- Animation frames: Control animation update frequency
- Network requests: Limit API call frequency
Throttle Implementation Principle
javascript// Simple throttle implementation function throttle(func, wait) { let timeout; let previous = 0; return function() { const context = this; const args = arguments; const now = Date.now(); if (now - previous > wait) { func.apply(context, args); previous = now; } else { clearTimeout(timeout); timeout = setTimeout(() => { func.apply(context, args); previous = Date.now(); }, wait - (now - previous)); } }; } // Usage example const throttledScroll = throttle(function() { console.log('Scroll position:', window.scrollY); }, 100); // While scrolling, executes at most every 100ms window.addEventListener('scroll', throttledScroll);
Using Lodash Throttle
javascriptimport _ from 'lodash'; // Basic usage const throttledFn = _.throttle(function() { console.log('Executed'); }, 100); // Immediate execution option const throttledImmediate = _.throttle(function() { console.log('Immediate execution'); }, 100, { leading: true, trailing: false }); // Cancel throttle const throttled = _.throttle(function() { console.log('Execute'); }, 100); throttled(); throttled.cancel(); // Cancel execution
Difference Between Debounce and Throttle
| Feature | Debounce | Throttle |
|---|---|---|
| Execution timing | After event stops | At fixed time intervals |
| Execution count | Only once | Possibly multiple times |
| Use cases | Search, form validation | Scroll, animation |
| Delay characteristic | Retimer on each trigger | Fixed time interval |
Visual Comparison
shellDebounce: Trigger: ●●●●●●●●●● Execute: ● Throttle: Trigger: ●●●●●●●●●● Execute: ● ● ● ●
Practical Application Examples
Search Box Debounce
javascriptimport _ from 'lodash'; class SearchComponent { constructor() { this.searchInput = document.getElementById('search-input'); this.debouncedSearch = _.debounce(this.performSearch.bind(this), 300); this.searchInput.addEventListener('input', this.handleInput.bind(this)); } handleInput(event) { const keyword = event.target.value; this.debouncedSearch(keyword); } performSearch(keyword) { console.log('Perform search:', keyword); // Send API request } }
Scroll Throttle
javascriptimport _ from 'lodash'; class ScrollHandler { constructor() { this.throttledScroll = _.throttle(this.handleScroll.bind(this), 100); window.addEventListener('scroll', this.throttledScroll); } handleScroll() { const scrollTop = window.scrollY; const windowHeight = window.innerHeight; const documentHeight = document.documentElement.scrollHeight; // Check if scrolled to bottom if (scrollTop + windowHeight >= documentHeight - 100) { this.loadMoreContent(); } } loadMoreContent() { console.log('Load more content'); // Logic to load more data } }
Performance Optimization Recommendations
-
Set reasonable delay times:
- Debounce: Usually 300-500ms
- Throttle: Usually 100-200ms
-
Clean up promptly:
javascript// Cancel when component unmounts componentWillUnmount() { this.debouncedFn.cancel(); this.throttledFn.cancel(); } -
Choose based on scenario:
- Need to wait for user operation completion → Use debounce
- Need continuous response but limit frequency → Use throttle
Summary
Debounce and throttle are both important performance optimization tools:
- Debounce is suitable for scenarios that need to wait for user operation completion, such as search and form validation
- Throttle is suitable for scenarios that need continuous response but limit frequency, such as scroll and animation
- Proper use of these two functions can significantly improve application performance and reduce unnecessary calculations and network requests
- Lodash provides complete implementations with various configuration options, it's recommended to use Lodash's version directly