Scenario: I have a Message page which contains a container whose left section contains contacts and groups to send message and right one has conversation flow. The conversation flow is loaded via ajax while on other hand clicking on any contact or group.this is what it looks like will load the contents on the right side using a javascript file which contains a setinterval function that executes every 5 seconds to check the database for new messages and grabs that message for displaying it in the conversation div.
Problem: on first load of the page, when i click a contact or group, obviously the content is loaded and the setinterval function runs right away. when i click another contact or group, loads the content again and executes the setinterval function again, problem is that there are now two setinterval function running when you try to look at the chrome developer tools. As you can see in this image, there are two requests now, 1 for contact and 1 for group since i clicked a contact and a group. And the requests keeps adding up upon clicking more contacts and groups.
This is the code for loading content via ajax when clicking on a contact or group:
$('.my_contacts a.list-group-item,.my_groups a.list-group-item,.new_message .list-group-item a').click(function(){
var href=$(this).attr('href');
$('.list-group-item').removeClass('active');
$(this).addClass('active');
$.ajax({
url:href,type:'post'
}).done(function(d){
$('#center-wing').html(d);
});
return false;
});
And this is the content inside the loaded ajax data:
...more html content here
<script>
$(function(){
$.getScript("res/js/custom/in-page/message.js");
});
</script>
And this is the code the runs every 5 seconds in message.js:
if(notification == true){
checkNewMsgId=setInterval(function(){
$.ajax({
url:'message/check_new_message/' + recipient + '/' + type,
type:'post'
}).done(function(d){
if(d.length > 0){
var obj={};
lastmsg.addClass('hide');
reset_inactivity();
for(var o in d){
var date=new Date(d[o].SentDate),time=format_time(date);
bubble_tpl_left.find('.bubble').attr('data-pk',d[o].Remarks);
if(d[o].SenderId == recipient){
lastmessagedate=format_date(date);
lastmessagetime=time;
}
if(type == 'CustomGroup') bubble_tpl_left.find('.msg_sender').removeClass('hide').html(d[o].FirstName + " " + d[o].LastName);
send(d[o].Reply,time,bubble_tpl_left);
obj.title=name;
obj.body=d[o].Reply;
}
if(pagehidden == true){
ding.play();push_notify(obj);
}else blop.play();
}
});
},5000);
}
...Sorry for the long post guys. Im really stuck at this one, ive tried clearing the interval before executing the setinterval.
Help will be much appreciated guys :)