Skip to content

Instantly share code, notes, and snippets.

@jbarnat
Created April 15, 2019 14:10
Show Gist options
  • Select an option

  • Save jbarnat/ee53849b92af70b85cdac51b77bf4a60 to your computer and use it in GitHub Desktop.

Select an option

Save jbarnat/ee53849b92af70b85cdac51b77bf4a60 to your computer and use it in GitHub Desktop.
ignore click event that occurs shortly after touchstart
export default function debounce(func: Function, sleep?: number): EventListener {
let timerMobile: number | undefined
let timer: number | undefined
return function debounced(e: Event): void {
if (!!timer || (!!timerMobile && e.type === "click")) {
return
}
func()
if (typeof sleep !== "undefined" && sleep > 0) {
clearTimeout(timer)
timer = setTimeout(() => {
timer = undefined
}, sleep)
}
if (e.type === "touchstart") {
clearTimeout(timerMobile)
timerMobile = setTimeout(() => {
timerMobile = undefined
}, 450)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment