【发布时间】:2015-07-26 17:16:43
【问题描述】:
我有一个脚本每秒查看一次电话呼叫队列并向用户显示更新。 “现在我的代码将消息写入控制台以进行测试。”
由于我的代码每 1 秒运行一次,因此当用户打开多个表时,同一函数每秒调用 1 x“总标签”。如果我打开了 5 个选项卡,即每秒 5 个请求,这可能会给用户提供虚假信息或导致问题。
有没有办法让我只在活动选项卡上运行setInterval() 函数?我的代码必须在应用程序的每个页面上执行,以确保在有呼入电话或他或她需要注意的事情时通知用户。
这是每秒执行的代码。
<script>
$(function(){
function isset(a, b){
if(typeof a !== "undefined" && a){
return a
}
return b;
}
setInterval(function() {
$.getJSON("showMEssages.php", {method: "getMessages"}, function(data){
if(typeof data.calls === 'undefined' || data.calls.length == 0 || !data.calls){
console.log('No Messages');
return;
}
$.each(data.calls, function(i, item){
$.each(item, function(z, c){
var interactionId = isset(c.interactionId, 0);
var Eic_CallDirection = isset(c.Eic_CallDirection, '');
var Eic_State = isset(c.Eic_State, '');
var AccoRDI_mid = isset(c.AccoRDI_mid, '');
var Eic_RemoteAddress = isset(c.Eic_RemoteAddress, '');
if(Eic_State == '' || Eic_CallDirection == ''){
return;
}
//incoming call that is not answered
if( Eic_CallDirection == 'I' && Eic_State == 'A'){
console.log('Incomming Call From ' + Eic_RemoteAddress + ' MID: ' + AccoRDI_mid );
return;
}
//on hold
if( Eic_State == 'H'){
console.log('Phone number ' + Eic_RemoteAddress + ' is on hold' );
return;
}
//voicemail
if( Eic_State == 'M'){
console.log('Phone number ' + Eic_RemoteAddress + ' is on leaving a voicemail' );
return;
}
//connected call
if(Eic_State == 'C'){
console.log('Live Call With ' + Eic_RemoteAddress );
return;
}
//Dialling call
if(Eic_State == 'O'){
console.log('Dialling ' + Eic_RemoteAddress );
return;
}
//Dialling call
if(Eic_State == 'R'){
console.log('Outbound call is rining and waiting for answer ' );
return;
}
//Call Disconnected
if(Eic_State == 'I' || Eic_State == 'E' ){
console.log('Hungup with ' + Eic_RemoteAddress );
return;
}
});
});
});
}, 1000);
});
</script>
有任何替代解决方案吗?
【问题讨论】:
-
见here
-
这可能是一个更好的答案:stackoverflow.com/questions/1060008/…
-
另外,如果出现问题,通常最好使用
setTimeout()而不是setInterval()。如果它仍应继续运行,只需在回调中重新初始化超时。 -
从服务器轮询...为什么不使用server-sent events 或web sockets?
-
@Mike 不确定我是否正确理解了您评论中的问题。在上面的代码示例中,您正在从
showMEssages.php轮询,而没有其他参数,例如用户名和密码。服务器发送事件的思想类似于long-polling:客户端(浏览器)向服务器发送请求;连接保持活动状态,服务器仅在有新数据时才响应。除非是跨域请求,否则客户端将发送 cookie。也许打开一个新问题或搜索 SO。
标签: javascript jquery