Created
September 21, 2011 15:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
The function only triggers once and caches the result for N milliseconds. That might not be the expected behavior for a debounce function.