Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An ES6 implementation of the debounce function. "Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in 'execute this function only if 100 milliseconds have passed without it being called.'" - CSS-Tricks (https://css-tricks.com/the-difference-between-throttling-and-debounc…
function debounce(callback, wait, immediate = false) {
let timeout = null
return function() {
const callNow = immediate && !timeout
const next = () => callback.apply(this, arguments)
clearTimeout(timeout)
timeout = setTimeout(next, wait)
if (callNow) {
next()
}
}
}
/**
* Normal event
* event | | |
* time ----------------
* callback | | |
*
* Call log only when it's been 100ms since the last sroll
* scroll | | |
* time ----------------
* callback | |
* |100| |100|
*/
const handleScroll = debounce((arg, event) => {
console.log(`${arg} ${event.type}`)
}, 100, true)
window.addEventListener('scroll', (event) => {
handleScroll('Event is:', event)
})
@rayfoss

This comment has been minimized.

Copy link

rayfoss commented Aug 28, 2017

this has serious context binding issues...
This underscore.js one worked without a hitch: https://davidwalsh.name/javascript-debounce-function

@GreenAsJade

This comment has been minimized.

Copy link

GreenAsJade commented Oct 7, 2017

@rayfoss I'm hunting for one that doesn't cause the toolchain in the project I'm using to complain about var and using this outside class context :( The underscore one gives me both those problems.

@jpenney1

This comment has been minimized.

Copy link

jpenney1 commented Mar 29, 2019

This simplified pure ES6 version of debounce utilizing arrow functions should work more predictably and have less issues with context binding. No new this context is created, rather, only a lexical namespace is allocated to allow the timeout to reset every time it's triggered until the appropriate amount of inactive time has elapsed.

const debounce = (callback, wait) => {
  let timeout = null
  return (...args) => {
    const next = () => callback(...args)
    clearTimeout(timeout)
    timeout = setTimeout(next, wait)
  }
}
@BjornLuG

This comment has been minimized.

Copy link

BjornLuG commented Aug 9, 2019

@jpenney1 Your example didn't have context binding at all. You're returning an arrow function which has no this context, so you can't bind it back to the callback. Instead, use a function expression to capture the context and re-apply it to the callback.
Here's what I have:

function debounce (fn, wait) {
  let t
  return function () {
    clearTimeout(t)
    t = setTimeout(() => fn.apply(this, arguments), wait)
  }
}
@jpenney1

This comment has been minimized.

Copy link

jpenney1 commented Aug 9, 2019

@BjornLuG arrow functions have implicit context binding, it's "bound" to the context of the containing scope.. or inherits it? Semantics.

If the function passed into the debounce has it's context already bound to this, then the arrow function calling it will allow it to will maintain it's original context bindings.

Below, using my pure debounce, I can bind the this to the function being debounced:

({
  namespace: function() {
    const functionCall = function() {console.log('this: ', this)}
    setTimeout(debounce(functionCall.bind(this), 1000))
  }
}).namespace()

Without the bind, this will be whatever the parent scope is for the debounce function itself.

Alternatively, passing in a pure function doesn't require a binding at all, as this will be appropriately bound:

({
  namespace: function() {
    const functionCall = () => console.log('this: ', this)
    setTimeout(debounce(functionCall), 1000))
  }
}).namespace()
@BjornLuG

This comment has been minimized.

Copy link

BjornLuG commented Aug 10, 2019

@jpenney1 I understand your example completely and I've tested my debounce function with your example, which works fine too. But I found a specific case on Reddit which your function fails.

Case:

const obj = {
  name: 'foo',
  sayMyName() {
    console.log('My name is', this.name)
  }
}

obj.sayMyName() //-> My name is foo
obj.deb = debounce(obj.sayMyName, 1000)
obj.deb() // Should log -> My name is foo

With your function, obj is not binded to your callback and will return My name is. So unless I explicitly bind the function:

obj.deb = debounce(obj.sayMyName.bind(obj), 1000)
obj.deb()

This will now log correctly. But the problem is that the explicit binding is somewhat unnatural, and the debounce function should handle it automatically for us.
With my function however, it logs correctly even without the explicit binding, outputting My name is foo.

I've done some extensive testing and so far only this test case had me scratching my head. I hope i'm not missing anything out here.

Cheers!

@andrioyou

This comment has been minimized.

Copy link

andrioyou commented Nov 6, 2019

Works great! Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.