$('.contact').click(function() {
$('.cont').not(this).removeClass('active');
$(this).addClass('active');
var limit = 8;
var start = 0;
sendRequest(limit, start);
loader();
function loader (){
var scrollTop = $('.messages').scrollTop();
if (scrollTop <= 0) {
$('.signal2').show();
} else {
$('.signal2').hide();
}
setTimeout(function() { loader(); }, 500);
};
function sendRequest(limit, start) {
var scrollPosition = $('.messages').scrollTop();
var scrollHeight = $('.messages')[0].scrollHeight;
var convo_id=document.getElementById("convo_id").value;
$.ajax({
cache: false,
type: "POST",
url: 'show_chat.php',
data: ({ convo_id: convo_id, limit: limit, start:start }),
success: function(data) {
alert(limit);
if (data != '') {
var scrollTop = $('.messages').scrollTop();
if (scrollTop <= 0) {
limit = limit + 8;
$('.messages').scrollTop(30);
}
}
if (scrollPosition + $('.messages').height() === scrollHeight) {
$('.messages').animate( { scrollTop:scrollHeight},700);
}
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(function(){ sendRequest(limit, start); }, 2000); // The interval set to 5 seconds
}
});
};
This is my code, I'll try my best to explain:
-
$('.contact').click(function() {
is when the user selects a contact person. -
limit
is the limit to the query that fetches the user chats. -
convo_id
is used to find the user conversation.
Now, everything works fine but, when i'm on a particular chat conversation, and i loaded more chats by scrolling the page to the top for 3 times, my current limit value would be 8*3=24
.
Therefore you can see i call this function function sendRequest(limit, start){
from the timeout
call passing the parameter (limit=24)
with an interval of 2 secs (keeping the chat page up to date).
But, the problem arises when i select a different contact person. The convo_id
changes and the $('.contact').click(function() {
calls sendRequest()
with the parameter (limit=8)
.
However, the same function is called by the timeout with the old parameter at the same time (limit=24)
. Therefore, the whole page flickers between displaying two sets of results to and fro (8 messages and 24 messages) every sec.