Created
July 23, 2012 11:24
-
-
Save karlwestin/3163157 to your computer and use it in GitHub Desktop.
throttling a window.scroll handler for better performance
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
// underscore's throttle-metod | |
var throttle = function(func, wait) { | |
var context, args, timeout, throttling, more, result; | |
var whenDone = _.debounce(function(){ more = throttling = false; }, wait); | |
return function() { | |
context = this; args = arguments; | |
var later = function() { | |
timeout = null; | |
if (more) func.apply(context, args); | |
whenDone(); | |
}; | |
if (!timeout) timeout = setTimeout(later, wait); | |
if (throttling) { | |
more = true; | |
} else { | |
result = func.apply(context, args); | |
} | |
whenDone(); | |
throttling = true; | |
return result; | |
}; | |
}; | |
/* | |
Old code: | |
$(window).scroll(function(e) { | |
// whatever | |
}); | |
*/ | |
// new code, break out scroll handler: | |
var myScrollHandler = function(e) { | |
//whatever | |
}; | |
$(window).scroll(throttle(myScrollhandler, 50)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment