Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shaneriley/c4b718929f10869163dc92e8f440472d to your computer and use it in GitHub Desktop.
Save shaneriley/c4b718929f10869163dc92e8f440472d to your computer and use it in GitHub Desktop.
Throttle and debounce
function throttle(delay, no_trailing, callback, debounce_mode) {
var timeout_id,
last_exec = 0;
if ( typeof no_trailing !== "boolean" ) {
debounce_mode = callback;
callback = no_trailing;
no_trailing = undefined;
}
function wrapper() {
var that = this,
elapsed = +new Date() - last_exec,
args = arguments;
function exec() {
last_exec = +new Date();
callback.apply( that, args );
}
function clear() { timeout_id = undefined; }
if ( debounce_mode && !timeout_id ) { exec(); }
timeout_id && clearTimeout( timeout_id );
if ( debounce_mode === undefined && elapsed > delay ) {
exec();
}
else if ( no_trailing !== true ) {
timeout_id = setTimeout( debounce_mode ? clear : exec, debounce_mode === undefined ? delay - elapsed : delay );
}
}
if ( $.guid ) {
wrapper.guid = callback.guid = callback.guid || $.guid++;
}
return wrapper;
}
export { throttle };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment