【发布时间】:2016-06-25 03:35:21
【问题描述】:
场景: 我有一个消息页面,其中包含一个容器,其左侧部分包含要发送消息的联系人和组,右侧有对话流。对话流通过 ajax 加载,另一方面单击任何联系人或组。this is what it looks like 将使用包含 setinterval 函数的 javascript 文件加载右侧的内容,该函数每 5 秒执行一次以检查数据库中的新消息并抓取该消息以将其显示在对话 div 中。
问题: 在第一次加载页面时,当我单击联系人或组时,显然内容已加载并且 setinterval 函数会立即运行。当我单击另一个联系人或组时,再次加载内容并再次执行 setinterval 函数,问题是当您尝试查看 chrome 开发人员工具时,现在有两个 setinterval 函数正在运行。 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。在点击更多联系人和群组时,请求会不断增加。
这是点击联系人或群组时通过 ajax 加载内容的代码:
$('.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;
});
这是加载的ajax数据里面的内容:
...more html content here
<script>
$(function(){
$.getScript("res/js/custom/in-page/message.js");
});
</script>
这是 message.js 中每 5 秒运行一次的代码:
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);
}
...对不起,长篇大论。我真的坚持这一点,我尝试在执行 setinterval 之前清除间隔。
帮助将不胜感激 :)
【问题讨论】:
-
如果您希望它只运行一次,请使用 setTimeout()