Skip to content

Instantly share code, notes, and snippets.

@Grohden
Last active May 20, 2020 01:46
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 Grohden/9d69c93aaad448a88c12519c80b2caa1 to your computer and use it in GitHub Desktop.
Save Grohden/9d69c93aaad448a88c12519c80b2caa1 to your computer and use it in GitHub Desktop.
// calls always the last
export const debounce = (time: number) => {
let timeout: ReturnType<typeof setTimeout> | null = null
return (fn: () => void) => {
if(timeout !== null) {
clearTimeout(timeout)
timeout = null
}
timeout = setTimeout(() => {
timeout = null
fn()
}, time)
}
}
// Executes within interval, ignores subsequent calls until first interval is reached
export const callUpdatedInInterval = (time: number) => {
let timeout: ReturnType<typeof setTimeout> | null = null
let currentFn: null | (() => void) = null
return (fn: () => void) => {
currentFn = fn
if(timeout !== null) {
return
}
timeout = setTimeout(() => {
timeout = null
currentFn?.()
currentFn = null
}, time)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment