Skip to content

Instantly share code, notes, and snippets.

@zeusdeux
Last active August 17, 2016 15:04
Show Gist options
  • Save zeusdeux/b1703412b6a8f5bd6643184e83eeebae to your computer and use it in GitHub Desktop.
Save zeusdeux/b1703412b6a8f5bd6643184e83eeebae to your computer and use it in GitHub Desktop.
Debounce and throttle?
// If multiple calls to fn are made within time t
// this will call fn only once after a delay of
// t milliseconds after the most recent call
function debounce1(fn, t) {
let timeout
return function (...args) {
let self = this
clearTimeout(timeout)
timeout = setTimeout(() => fn.apply(self, args), t)
}
}
// this will call fn only once within an interval of time t
// it will call fn with the arguments provided in the
// most recent call before the timer expires
// Is this throttle?
function debounce2(fn, t) {
let timeout = null
let latestSelf, latestArgs
return function (...args) {
latestSelf = this
latestArgs = args
if (timeout) return
timeout = setTimeout(() => {
fn.apply(latestSelf, latestArgs)
timeout = null
}, t)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment