Skip to content

Instantly share code, notes, and snippets.

@jasonwyatt
Created September 21, 2011 15:00
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jasonwyatt/1232271 to your computer and use it in GitHub Desktop.
Save jasonwyatt/1232271 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;
};
};
@electerious
Copy link

The function only triggers once and caches the result for N milliseconds. That might not be the expected behavior for a debounce function.

[…] a function, that, as long as it continues to be invoked, will not be triggered. The function will be called after it stops being called for N milliseconds. (https://davidwalsh.name/javascript-debounce-function)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment