Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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;
};
};

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