Skip to content

Instantly share code, notes, and snippets.

@maxwihlborg
Created March 1, 2015 15:17
Show Gist options
  • Save maxwihlborg/1911a28f988444db3ddc to your computer and use it in GitHub Desktop.
Save maxwihlborg/1911a28f988444db3ddc to your computer and use it in GitHub Desktop.
Simple javascript debounce function used when bundling up function calls.
/**
* Simple debounce function; usage:
*
* Create a function that only can be called once every 500 ms
*
* var df = debounce(function() {
* ... func body ...
* }, 500)
*
* Bind the function to an event
*
* document.addEventListener('keydown', df);
*
* @param fn {function} function you want to debounce
* @param wait {number} interval wait in ms
*/
function debounce(fn, wait) {
var timeout;
return function() {
var ctx = this, args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function() {
fn.apply(ctx, args);
}, wait || 100);
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment