Last active
February 29, 2016 14:52
-
-
Save jli168/a1a43df1b2abdb4d8fee to your computer and use it in GitHub Desktop.
javascript debounce function
This file contains hidden or 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
// call func after a defined interval of time | |
var debounce = function( func, wait ) { | |
var timeoutId = null; | |
// set default interval time | |
wait = wait || 200; | |
return function() { | |
var args = arguments, | |
context = this; | |
window.clearTimeout( timeoutId ); | |
timeoutId = window.setTimeout( function() { | |
timeoutId = null; | |
func.apply( context, args); | |
}, wait ); | |
}; | |
}; | |
// remember: debounce() will return a function to call "func", so you have to call this debounce() function eventually! | |
var oldFunc = function(){ | |
// ... | |
}; | |
var newFunc = debounce( oldFunc, 1000 ); | |
// now you can bind this new function to an event: | |
$domObj.on("keydown", newFunc ); | |
// reference: http://stackoverflow.com/questions/24004791/can-someone-explain-the-debounce-function-in-javascript |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment