Skip to content

Instantly share code, notes, and snippets.

@karlwestin
Created July 23, 2012 11:24
Show Gist options
  • Save karlwestin/3163157 to your computer and use it in GitHub Desktop.
Save karlwestin/3163157 to your computer and use it in GitHub Desktop.
throttling a window.scroll handler for better performance
// 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