Reputation: 3666
I have an infinite scroll set up with the following piece of code.
$(window).scroll(function () {
if ($(window).scrollTop() >= $("#home_content").height() - $(window).height()) {
if (isLastPage) {
foo();
} else {
bar(); // JQuery AJAX call
}
}
});
This is inside document.ready(); The ajax call doesn't happen when the server sends a flag for the last page. This works fine in a normal scenario. But when I press F5(Refresh) from the bottom of the page, two simultaneous scroll events are fired,and it bypasses the flag (as the second call happens even before the flag is set) and duplicate data is loaded.
The only thing i know is it happens at the end of document.ready() function. Anyone, any idea??
Thanks in advance.
EDIT
There is no much relevant code other than this.
And this happens only in FF 17. In IE 9 when I do a fast scroll down, same scroll is fired twice
Upvotes: 1
Views: 2712
Reputation: 18387
You can use this debounce routine for all sort of event calls. Clean and reusable.
// action takes place here.
function infinite_scrolling(){
if ($(window).scrollTop() >= $("#home_content").height() - $(window).height()) {
if (isLastPage) {
foo();
} else {
bar(); // JQuery AJAX call
}
}
}
// debounce multiple requests
var _scheduledRequest = null;
function infinite_scroll_debouncer(callback_to_run, debounce_time) {
debounce_time = typeof debounce_time !== 'undefined' ? debounce_time : 800;
if (_scheduledRequest) {
clearTimeout(_scheduledRequest);
}
_scheduledRequest = setTimeout(callback_to_run, debounce_time);
}
// usage
$(document).ready(function() {
$(window).scroll(function() {
infinite_scroll_debouncer(infinite_scrolling, 1000);
});
});
Upvotes: 2
Reputation: 74420
This is just a workaround as we cannot see your complete code, but maybe thats can help:
var timeout;
$(window).scroll(function(){
clearTimeout(timeout);
timeout = setTimeout(function(){
if ($(window).scrollTop() >= $("#home_content").height() - $(window).height()){
if (isLastPage){
foo();
}else{
bar();//AJAX call
}
}
},0);
});
Upvotes: 1