Prevent jquery get and add duplicated data when the scrollbar remain at bottom of div for too long?
I have a div, when user 开发者_JS百科scroll to bottom of div, jquery will get more data from other page and add it to the div. My problem is sometime the scrollbar remain at bottom of div for too long, so it execute jquery statement for multiple times. Jquery get and add duplicated data to the div. How to prevent jquery get and add duplicated data when the scrollbar remain at bottom of div for too long? My codes :
function scrollalert(){
var elements = $(".messagepiecetime");
var lastmsgid = elements.eq(elements.length - 1).attr('id');
var scrolltop=$('#scrollbox').attr('scrollTop');
var scrollheight=$('#scrollbox').attr('scrollHeight');
var windowheight=$('#scrollbox').attr('clientHeight');
var scrolloffset=20;
if(scrolltop>=(scrollheight-(windowheight+scrolloffset)))
{
$.get('test7a.php?lastmsgID=' + lastmsgid, '', function(newitems){
$('#content').append(newitems);
});
}
setTimeout('scrollalert();', 1000);
}
setTimeout('scrollalert();', 1000);//
this is where the problem happen. The problem is fixed if I set it to 3000 miliseconds. Output will be 8 duplicated data if I set it to 1 milisecond. I know set 3k miliseconds can fix the problem, but I don't want users wait for 3 seconds to get new data every they scroll to bottom. Is there any other way to fix it without using setTimeout 3 seconds?
You could set a global variable that will flag if more data should be loaded.
var loadMore = true;
function scrollalert() {
var elements = $(".messagepiecetime");
var lastmsgid = elements.eq(elements.length - 1).attr('id');
var scrolltop = $('#scrollbox').attr('scrollTop');
var scrollheight = $('#scrollbox').attr('scrollHeight');
var windowheight = $('#scrollbox').attr('clientHeight');
var scrolloffset = 20;
if ((scrolltop >= (scrollheight - (windowheight + scrolloffset))) && loadMore) {
loadMore = false;
$.get('test7a.php?lastmsgID=' + lastmsgid, '', function(newitems) {
$('#content').append(newitems);
loadMore = true;
});
}
setTimeout('scrollalert();', 1000);
}
精彩评论