Skip to content

Instantly share code, notes, and snippets.

@eliascotto
Created August 19, 2021 06:15
Show Gist options
  • Save eliascotto/7f8566c86c70da6643265f8bdcdadd43 to your computer and use it in GitHub Desktop.
Save eliascotto/7f8566c86c70da6643265f8bdcdadd43 to your computer and use it in GitHub Desktop.
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