Skip to content

Instantly share code, notes, and snippets.

@vincentorback
Last active September 28, 2023 16:24
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save vincentorback/9649034 to your computer and use it in GitHub Desktop.
Save vincentorback/9649034 to your computer and use it in GitHub Desktop.
Smarter debouncing
export function debounce (fn, wait = 1) {
let timeout
return function (...args) {
clearTimeout(timeout)
timeout = setTimeout(() => fn.call(this, ...args), wait)
}
}
function debounce (fn, wait) {
var timeout
return function () {
clearTimeout(timeout)
var args = arguments
timeout = setTimeout(function () {
fn.apply(this, args)
}, (wait || 1))
}
}
window.addEventListener('resize', debounce(function () {
}, 500))
@kutyel
Copy link

kutyel commented Jun 14, 2017

What about this?

export function debounce(fn, wait = 1) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn.call(this, ...args), wait);
  }
}

I think it looks more ES2015 :)

@vincentorback
Copy link
Author

@kutyel yummy!

@katzgrau
Copy link

katzgrau commented Apr 12, 2020

Think there may be a bug in debounce-vanilla.js in passing the correct arguments object. Here's the fixed version:

function debounce (fn, wait) {
  var timeout
  return function () {
    clearTimeout(timeout)
    var args = arguments;
    timeout = setTimeout(function () {
      fn.apply(this, args)
    }, (wait || 1))
  }
}

@vincentorback
Copy link
Author

@katzgrau you're very right! Thank you!

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