forked from priyankashrama/JavaScript-Program
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebounce.js
More file actions
29 lines (25 loc) · 649 Bytes
/
Copy pathdebounce.js
File metadata and controls
29 lines (25 loc) · 649 Bytes
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
// filename: debounce.js
// Usage: node debounce.js
// Example demonstrates debounce with a simple simulated rapid calls.
function debounce(fn, wait) {
let timeoutId = null;
return function(...args) {
if (timeoutId) clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
fn.apply(this, args);
timeoutId = null;
}, wait);
}
}
// Example:
function onResize() {
console.log('Resized at', new Date().toISOString());
}
const debouncedResize = debounce(onResize, 300);
// Simulate rapid calls:
let i = 0;
const interval = setInterval(() => {
debouncedResize();
i++;
if (i >= 10) clearInterval(interval);
}, 50);