Skip to content

Instantly share code, notes, and snippets.

@mlshv
Created December 11, 2020 08:25
Show Gist options
  • Save mlshv/1421b6ace6156edef9b84bf2b33746ef to your computer and use it in GitHub Desktop.
Save mlshv/1421b6ace6156edef9b84bf2b33746ef to your computer and use it in GitHub Desktop.
useTimeout
import { useState, useEffect } from 'react'
const removeKeyFromState = (key, setState) => {
setState(({ [key]: deletedKey, ...restKeys }) => ({ ...restKeys }))
}
const useTimeout = () => {
const [timeouts, setTimeouts] = useState({})
useEffect(() => {
return () => Object.values(timeouts).forEach(window.clearTimeout)
}, [])
const createTimeout = (callback, time, id = Math.random().toString()) => {
if (timeouts[id]) {
window.clearTimeout(timeouts[id])
}
const timeout = window.setTimeout(() => {
callback()
removeKeyFromState(id, setTimeouts)
}, time)
setTimeouts((oldTimeouts) => ({ ...oldTimeouts, [id]: timeout }))
}
const cancelTimeout = (id) => {
window.clearTimeout(timeouts[id])
removeKeyFromState(id, setTimeouts)
}
return { createTimeout, cancelTimeout }
}
export default useTimeout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment