Throttle
Limits a function to execute once every X ms.
Use Case: Limit frequency of rapievents.ts
Example Use: Scroll, resize, Location updates (e.g., GPS), button taps
Example: Scroll Event
import throttle from 'lodash/throttle';
const handleScroll = throttle((event) => {
console.log('Scrolling...', event.nativeEvent.contentOffset.y);
}, 1000); // Only once every 1 second
<ScrollView onScroll={handleScroll} scrollEventThrottle={16} />
π Even if the scroll event fires 60 times per second, your handler only fires once every 1000 ms.
Debounce
Waits until a function hasn't been called for X ms.
Use Case: React to the final event after user stops
Example Use: Text search, Form validation while typing, autocomplete, form
Example: Text Input
import debounce from 'lodash/debounce';
const handleChange = debounce((text) => {
console.log('Searching for:', text);
}, 500); // Only runs 500ms after user stops typing
<TextInput onChangeText={handleChange} />
β³ The user types "h-e-l-l-o," and the function fires once, after the user pauses for 500 ms.
What debounce() Does Internally:
When you call:
debounce((text) => { ... }, 500)
β¦it wraps your function in a way that:
- Every time the function is called (e.g., from onChangeText while typing),
- It resets a timer (using setTimeout)
- The actual function only runs if the timer completes without interruption (i.e., you stop typing for ms).
Utility Code Without Lodash (Optional)
You can write your own too:
function debounce(fn, delay) {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => fn(...args), delay);
};
}
function throttle(fn, limit) {
let inThrottle;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => (inThrottle = false), limit);
}
};
}
Top comments (0)