-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebounce-function.js
More file actions
37 lines (32 loc) · 1.11 KB
/
debounce-function.js
File metadata and controls
37 lines (32 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Title: Debounce Function
// Description: Delays function execution until after a pause in calls
// Author: @VasudevJaiswal
// Tags: performance, events, utility, optimization
// Usage: const debouncedSearch = debounce(search, 300);
/**
* Creates a debounced version of a function.
* The debounced function delays invoking the original function
* until after `delay` milliseconds have elapsed since the last call.
*
* @param {Function} fn - The function to debounce
* @param {number} delay - Delay in milliseconds
* @returns {Function} Debounced function
*/
function debounce(fn, delay = 300) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
// Example usage
const searchInput = document.getElementById("search");
function handleSearch(event) {
console.log("Searching for:", event.target.value);
// Make API call here
}
// Only fires 300ms after the user stops typing
const debouncedSearch = debounce(handleSearch, 300);
searchInput?.addEventListener("input", debouncedSearch);