我有一个脚本,每秒查看一个电话呼叫队列,并向用户显示更新。 “现在我的代码将消息写入控制台以进行测试。”
由于我的代码每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>
对此有任何替代解决方案吗?
答案 0 :(得分:0)
您可以实现某种机制来同步不同选项卡之间的工作。主要想法是让标签彼此沟通
例如,一旦用户打开标签页,您就会向一个频道广播一条消息,说明它&#34;我正在寻找活动标签&#34;。然后,活动标签(在同一频道上收听)将响应:&#34;我还活着#34;,新打开的标签将不会启动间隔功能。否则它将启动间隔并将其自身标记为活动。在实践中,您可能需要做其他事情以消除死锁(例如使用看门狗技术)
还有其他方法可以做到,但一般的想法是让标签彼此沟通
一些可能帮助您实现它的库
答案 1 :(得分:0)
我认为最好在执行setTimeout
回调之前设置一个可以检查的标记,您可以使用window.onfocus
和window.onblur
知道标签是否有焦点:< / p>
var tabHasFocus = true;
window.onfocus = function() {
tabHasFocus = true;
}
window.onblur = function() {
tabHasFocus = false;
}
setInterval(function() {
if(tabHasFocus) {
...
}
}, 1000);