Skip to content

Instantly share code, notes, and snippets.

@karlpokus
Created February 8, 2017 16:00
Show Gist options
  • Save karlpokus/3846264ebd1f37bf012009adf929ba02 to your computer and use it in GitHub Desktop.
Save karlpokus/3846264ebd1f37bf012009adf929ba02 to your computer and use it in GitHub Desktop.
debounce in js
// from underscore.js
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// [wait] milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounceOG(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
// debounce without the option to call immediately
function debounce(fn, wait) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
fn.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
// create
var taxingCalc = debounce(function() {
// All the taxing stuff you do
}, 500);
// apply
window.addEventListener('resize', taxingCalc);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment