Created
August 19, 2021 06:15
-
-
Save eliascotto/7f8566c86c70da6643265f8bdcdadd43 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef } from "react"; | |
export default function useThrottle(callback, delay) { | |
const savedTimer = useRef(null) | |
function execCallback(...args) { | |
// Create a timeout and block other calls until this callback is resolved | |
savedTimer.current = setTimeout(() => { | |
if (typeof callback === "function") { | |
callback(...args) | |
} | |
savedTimer.current = null | |
}, delay) | |
} | |
return { | |
exec: (...args) => { | |
// Execute only if no other callback is waiting | |
if (!savedTimer.current) { | |
execCallback(...args) | |
} | |
}, | |
clear: () => { | |
// Clear the current timeout | |
if (savedTimer.current) { | |
clearTimeout(savedTimer.current) | |
} | |
} | |
} | |
} | |
function MyComponent() { | |
const saveContent = useThrottle(saveContentToLocalStorage, 2000) | |
function saveContentToLocalStorage(content) { | |
localStorage.setItem("mykey", content) | |
} | |
const handleSaveClick = () => { | |
saveContent.exec("mycontent") | |
} | |
const handleCancelClick = () => { | |
saveContent.clear() | |
} | |
return ( | |
<> | |
<div onClick={handleSaveClick}>Save</div> | |
<div onClick={handleCancelClick}>Cancel</div> | |
</> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment