Skip to content

Instantly share code, notes, and snippets.

@CVertex
Forked from jasonwyatt/debouncer.js
Created July 7, 2016 06:57
Show Gist options
  • Save CVertex/0cd6281e041b81aa89ca8717070ad7eb to your computer and use it in GitHub Desktop.
Save CVertex/0cd6281e041b81aa89ca8717070ad7eb to your computer and use it in GitHub Desktop.
How to **correctly** debounce an event that will be triggered many times with identical arguments.
function debounce(fn, debounceDuration){
// summary:
// Returns a debounced function that will make sure the given
// function is not triggered too much.
// fn: Function
// Function to debounce.
// debounceDuration: Number
// OPTIONAL. The amount of time in milliseconds for which we
// will debounce the function. (defaults to 100ms)
debounceDuration = debounceDuration || 100;
return function(){
if(!fn.debouncing){
var args = Array.prototype.slice.apply(arguments);
fn.lastReturnVal = fn.apply(window, args);
fn.debouncing = true;
}
clearTimeout(fn.debounceTimeout);
fn.debounceTimeout = setTimeout(function(){
fn.debouncing = false;
}, debounceDuration);
return fn.lastReturnVal;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment