forked from priya42bagde/JavaScriptCodingInterviewQuestions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDebaouncing and Throttling
More file actions
61 lines (54 loc) · 1.37 KB
/
Copy pathDebaouncing and Throttling
File metadata and controls
61 lines (54 loc) · 1.37 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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import React, { useEffect } from "react";
export default function App() {
// Logs when input changes (debounced)
const handleChange = (e) => {
console.log("Debouncing");
};
// Logs when mouse moves (throttled)
const handleMouseMove = (e) => {
console.log("Throttling");
};
// Debounce utility function
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(this, args);
}, delay);
};
}
// Throttle utility function
function throttle(func, delay) {
let run = false;
return function (...args) {
if (!run) {
func(...args);
run = true;
setTimeout(() => {
run = false;
}, delay);
}
};
}
// Add throttled mousemove listener when component mounts
useEffect(() => {
const throttledMouseMove = throttle(handleMouseMove, 2000);
window.addEventListener("mousemove", throttledMouseMove);
// Cleanup
return () => {
window.removeEventListener("mousemove", throttledMouseMove);
};
}, []);
return (
<div style={{ padding: "2rem" }}>
<h2>Debounce Input Example</h2>
<input
type="text"
placeholder="Start typing..."
onChange={debounce(handleChange, 500)}
style={{ padding: "10px", fontSize: "16px" }}
/>
</div>
);
}