Skip to content

Instantly share code, notes, and snippets.

@electerious
Forked from jasonwyatt/debouncer.js
Last active December 12, 2018 08:18
Show Gist options
  • Save electerious/2a49a51c62c9a71c8454 to your computer and use it in GitHub Desktop.
Save electerious/2a49a51c62c9a71c8454 to your computer and use it in GitHub Desktop.
How to **correctly** debounce an event that will be triggered many times with identical arguments.
const debounce = function(fn, duration) {
let timeout = null
return (...args) => {
clearTimeout(timeout)
timeout = setTimeout(() => fn(...args), duration)
}
}
@electerious
Copy link
Author

Example:

const fn = (text) => console.log(text)
const dfn = debounce(fn, 200)

dfn('hello')
dfn('hello') // hello

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment