Skip to content

Instantly share code, notes, and snippets.

@maxmarinich
Last active May 21, 2020 16:18
Show Gist options
  • Save maxmarinich/2cb04ec5ba16fcfa360826a8b06d7afe to your computer and use it in GitHub Desktop.
Save maxmarinich/2cb04ec5ba16fcfa360826a8b06d7afe to your computer and use it in GitHub Desktop.
export function debounce(func, ms = 0) {
let timer = null
return function(...args) {
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(() => {
func.apply(this, args)
timer = null
}, ms)
}
}
export function throttle(func, ms) {
let isThrottled, savedArgs, savedThis
return function() {
if (isThrottled) {
savedArgs = arguments
savedThis = this
return
}
func.apply(this, arguments)
isThrottled = true
setTimeout(function() {
isThrottled = false
if (savedArgs) {
func.apply(savedThis, savedArgs)
savedArgs = savedThis = null
}
}, ms)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment