Skip to content

Instantly share code, notes, and snippets.

@sibnerian
Last active July 10, 2019 20:15
Show Gist options
  • Save sibnerian/95fb0d0b63cdc1241819 to your computer and use it in GitHub Desktop.
Save sibnerian/95fb0d0b63cdc1241819 to your computer and use it in GitHub Desktop.
Small, debounce function that works in Node and Browser
// Plucked from http://davidwalsh.name/javascript-debounce-function
// If you do use this in production, you should probably minify it
var debounce = function (func, wait, immediate) {
var timeout = null;
return function () {
var context = this;
var args = arguments;
var later = function() {
timeout = null;
if (!immediate) {
func.apply(context, args);
}
};
var callNow = immediate && !(timeout === null);
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
func.apply(context, args);
}
};
};
// Load the script in browser/node/commonJS environments
this.debounce = debounce;
// Slightly more defensive than tyepof module !== 'undefined'; this won't error if module === null.
if (typeof module !== 'undefined' && module !== null && module.exports) {
module.exports = debounce;
}
@homostellaris
Copy link

homostellaris commented Jul 10, 2019

I think there's an error here. The null check on line 15 should be inverted should it not?

var callNow = immediate && timeout === null;

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