Skip to content

Instantly share code, notes, and snippets.

@codegino
Created January 13, 2022 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codegino/c0cb9686746e2a2897051b4c31ec8ef4 to your computer and use it in GitHub Desktop.
Save codegino/c0cb9686746e2a2897051b4c31ec8ef4 to your computer and use it in GitHub Desktop.
Debounce Plain JavaScript
const debounce = (callback, wait) => {
let timeoutId = null;
return (...args) => {
window.clearTimeout(timeoutId);
timeoutId = window.setTimeout(() => {
callback.apply(null, args);
}, wait);
};
}
import React from 'react';
function App() {
const [mouseX, setMouseX] = React.useState(null);
const handleMouseMove = React.useMemo(
debounce((ev) => {
setMouseX(ev.clientX);
}, 250),
[]
);
return (
<div onMouseMove={handleMouseMove}>
Mouse position: {mouseX}
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment