I have this infinite scroll function set up on several of my pages. It works perfectly fine, but the Ajax call to load more items makes several database calls and it has to load a lot of images each time, and it usually takes several seconds to load. I've timed it at between 3 and 7 seconds depending on my connection. Because of this, it can turn into a real train wreck when the browser decides to fire the scroll event several times. How could I go about throttling or debouncing it so that the browser doesn't run the Ajax call several times in the span of a few seconds and grind everything to a halt?
$(document).ready()
{
//Infinite scroll
$(window).on('scroll', _.debounce( function(){
var height = $(window).height();
var scrollTop = $(window).scrollTop();
var dHeight = getDocHeight();
if( height + scrollTop >= dHeight - 100)
{
//Display items that were previously hidden
showAllItems();
if(!vloaded < START_NUM && !done){
//Load next set of items
$.ajax
({
type: "POST",
url: "/organizer/getMore",
data: { filter: vfilter, loaded: vloaded },
dataType: "html",
success: function( responseText, textStatus, XHR )
{
if(responseText.indexOf("// GRID ENTRY //") < 0){ //Out of items to load
done = true;
}
else{
//Display items that were previously hidden
showAllItems();
// select the element with the ID grid and insert the HTML
$( "#grid" ).append( responseText );
//alert("Loaded "+vloaded+" items");
}
}
});
// global variable
vloaded +=LOAD_NUM;
} // if
}
}
}, 500, true)); // on
} // ready
EDIT:
I downloaded underscore and added the debounce function, but now the Ajax call doesn't seem to be running at all. Even if I hadn't set immediate to true it should execute pretty quickly after I stop scrolling, but it doesn't execute at all.