Debounced Event Listener
Inspired by http://paulirish.com/2009/throttled-smartresize-jquery-event-handler/ which in turn was inspired by http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
HTML
<a href="#test">TEST</a>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
Scroll
JavaScript
/***
* Debounced event listener
* Created by @laustdeleuran and @emilchristensen
*
* Code hijacked and inspired by
* http://paulirish.com/2009/throttled-smartresize-jquery-event-handler/
* which in turn was inspired by
* http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
*
* Tested successfully in:
* - Chrome 13, Windows 7
* - FireFox 5, Windows 7
* - Opera 11.5, Windows 7
* - Safari 5.1, Windows 7
* - Internet Explorer 9, Windows 7
*
* IE6-8 (only tested in IE8) will run head-first into this problem:
* http://javascriptfixer.com/member-not-found.php
* when passing an eventObject through the function bound via smartbind.
* See also:
* http://stackoverflow.com/questions/3531751/member-not-found-ie-error-ie-6-7-8
***/
(function($,smartbind){
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
func.apply(obj, args);
};
if (timeout) {
clearTimeout(timeout);
} else if (execAsap) {
func.apply(obj, args);
return;
}
timeout = setTimeout(delayed, threshold || 200);
};
}
// Smartbind
jQuery.fn[smartbind] = function(event,func,threshold,execAsap){ return func ? this.bind(event, debounce(func,threshold,execAsap)) : this.trigger(event); };
})(jQuery,'smartbind');
// Example usage
$('a').smartbind('click',function(e){
e.preventDefault();
alert("smartclick");
},1000);
$(window).smartbind('scroll',function(){
setTimeout(alert("smartscroll",150));
});