Debounce
Serhii Shramko /
const debounce = (callback: TimerHandler, wait: number) => {
let timeoutId = null;
return (...args) => {
window.clearTimeout(timeoutId);
timeoutId = window.setTimeout(() => {
callback.apply(null, args);
}, wait);
};
}
Usage
In this example, nothing will happen until the user starts moving the mouse, and then stops moving it for at least 250ms.
interface MousePosition {
x: number | null;
y: number | null;
}
function MouseTracker() {
const [mousePosition, setMousePosition] = React.useState<MousePosition>({
x: null,
y: null
});
const handleMouseMove = React.useMemo(
() => debounce((event: React.MouseEvent) => {
setMousePosition({
x: event.clientX,
y: event.clientY
});
}, 250),
[]
);
return (
<div
onMouseMove={handleMouseMove}
className="w-full h-screen bg-gray-100"
>
<p>
Mouse X: {mousePosition.x}
<br />
Mouse Y: {mousePosition.y}
</p>
</div>
);
}