Skip to content

Instantly share code, notes, and snippets.

@alexsasharegan
Last active March 17, 2017 17:42
Show Gist options
  • Save alexsasharegan/32b9e9ed2eb4bcc16d63d537e24ab526 to your computer and use it in GitHub Desktop.
Save alexsasharegan/32b9e9ed2eb4bcc16d63d537e24ab526 to your computer and use it in GitHub Desktop.
Hijacking the useful debounce function from underscore.js
function debounce( func, wait, immediate ) {
let timeout;
let args;
let context;
let timestamp;
let result;
const now = Date.now || () => new Date().getTime();
const later = function () {
const last = now() - timestamp;
if ( last < wait && last >= 0 ) {
timeout = setTimeout( later, wait - last );
} else {
timeout = null;
if ( !immediate ) {
result = func.apply( context, args );
if ( !timeout ) context = args = null;
}
}
};
return function () {
context = this;
args = arguments;
timestamp = now();
const callNow = immediate && !timeout;
if ( !timeout ) timeout = setTimeout( later, wait );
if ( callNow ) {
result = func.apply( context, args );
context = args = null;
}
return result;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment