function public_showmsg(){
var timestamp,onlineTime;
timestamp = Date.parse(new Date())/1000;//获取当前时间的时间戳
onlineTime=timestamp - last_login_time;
$(".chat-conv").html('');
$(".tixingBox").html('');
var changeUrl = "ajax.php?n=index&h=showmsg"+"&sid="+Math.random();
$.get(changeUrl,function(str){
c_msg=str;
switch(str){
case "no_login":
//alert('未登陆,转向登陆页');
//location.href = "index.php?n=login";
break;
case '0':
$(".chat-conv").html("<p>您有<a href='#'>0条新消息</a></p>");
$(".tixingBox").html("最新提醒(0)");
break;
default:
strArr = str.split('|');
$(".chat-conv").html(strArr[0]);
$(".tixingBox").html(strArr[1]);
//播放提示声音
if(strArr[2] =='new_message') {
try{play("/public/system/flash/new_message.mp3");}catch(error){}
//play("/public/system/flash/new_message.mp3");
}
if($.cookie('cmsg')!=c_msg&&$.cookie('cmsg')!=''){
//展开
$('.chat-window').slideDown();
$.cookie('thestaus','0');
$('.tixingBox').addClass("tixingBox3");
}
else if($.cookie('thestaus')!=1){
$('.chat-window').slideDown();
$('.tixingBox').addClass("tixingBox3");
}
break;
}
});
/*1、模拟频率:
1.1 在线五分钟以内 1分钟模拟一次;
1.2 在线10分钟以内 2分钟模拟一次;
1.3 在线10-30分钟 3分钟模拟一次;
1.4 30分钟以上 4分钟一次;
1.5 每次模拟都必须显示,不沿用之前的概率原则
*/
//setInterval("public_showmsg();", 6000);
if(onlineTime < 300){
if(k) clearTimeout(k);
k=setTimeout("public_showmsg();", 60000);
}else if(onlineTime >= 300 && onlineTime < 600 ){
if(k) clearTimeout(k);
setTimeout("public_showmsg();", 120000);
}else if(onlineTime >= 600 && onlineTime < 1800){
if(k) clearTimeout(k);
setTimeout("public_showmsg();", 180000);
}else{
if(k) clearTimeout(k);
setTimeout("public_showmsg();", 60000);
}
}
$(function(){
public_showmsg;
});
如果 setTimeout用setInterval替代,直接会导致 机器死机,cpu占有过大,原因是:
setInterval是,每调用一次,多一个循环
setInterval是定时执行的,
第1次运行public_showmsg后,启动了setInterval,6秒后再次调用public_showmsg,又启动一次setInterval并调用public_showmsg,如此循环下去,CPU当然吃不消了
如果是setInterval就不应该放在函数内部,如果要放在函数内部就应该用setTimeout