Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created February 2, 2010 13:47
Show Gist options
  • Save cowboy/292677 to your computer and use it in GitHub Desktop.
Save cowboy/292677 to your computer and use it in GitHub Desktop.
Throttle + Debounce
/*!
* Throttle + Debounce - v0.2 - 2/5/2010
* http://benalman.com/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Returns a function that will, when called repeatedly, execute `callback` no
// more than once every `delay` milliseconds. After the function stops being
// called, it will execute one final time after approximately `delay`
// milliseconds (but only if necessary). If delay is 0 or omitted, `callback`
// will execute every time.
function throttle_debounce( callback, delay ) {
var timeout_id,
last_updated = 0;
return function() {
var now = +new Date,
that = this,
args = arguments;
function fn() {
callback.apply( that, args );
};
if ( !delay || now - last_updated > delay ) {
last_updated = now;
fn();
} else {
timeout_id && clearTimeout( timeout_id );
timeout_id = setTimeout( fn, delay );
}
};
};
/*
// Example:
$(function(){
function log_coords(e) {
console.log( e.pageX + ',' + e.pageY );
};
$('body').mousemove( throttle_debounce( log_coords, 1000 ) );
});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment