在twilio php中断开连接调用后停止计时器

时间:2018-09-04 05:16:15

标签: javascript php jquery twilio

我正在使用twilio api使用php中的调用连接和断开模块,每当断开连接时计时器都不会停止,这是我的代码

//当点击“答案”按钮时定时器启动

$('#answer').on('click', function() {

var countdown = document.getElementsByTagName('countdown')[0],
    start = document.getElementById('start'),
    stop = document.getElementById('stop'),
    clear = document.getElementById('clear'),
    seconds = 0, minutes = 0, hours = 0,
    t;

function add() {
    seconds++;
    if (seconds >= 60) {
        seconds = 0;
        minutes++;
        if (minutes >= 60) {
            minutes = 0;
            hours++;
        }
    }
countdown.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);

document.getElementById('checkyear').value = countdown.textContent;
    timer();
}
function timer() {
    t = setTimeout(add, 1000);
}
timer();
 }); 

//当断开通话时,计时器应停止

Twilio.Device.disconnect(function (conn) {
    clearTimeout(t);
    });

1 个答案:

答案 0 :(得分:1)

这里是Twilio开发人员的传播者。

我认为这里的问题是范围之一。变量t(设置为您用来计数时间的超时ID)仅在单击答案按钮时调用的事件处理函数中可用。

当它位于Twilio.Device.disconnect处理程序中时,tundefined

我将重新排列代码,以使计时变量和函数不在click事件处理程序的范围内,因此它们属于disconnect处理程序的范围。像这样:

var t, seconds, minutes, hours;

Twilio.Device.disconnect(function(conn) {
  clearTimeout(t);
});

function add() {
  seconds++;
  if (seconds >= 60) {
    seconds = 0;
    minutes++;
    if (minutes >= 60) {
      minutes = 0;
      hours++;
    }
  }
  countdown.textContent =
    (hours ? (hours > 9 ? hours : '0' + hours) : '00') +
    ':' +
    (minutes ? (minutes > 9 ? minutes : '0' + minutes) : '00') +
    ':' +
    (seconds > 9 ? seconds : '0' + seconds);

  document.getElementById('checkyear').value = countdown.textContent;
  timer();
}

function timer() {
  t = setTimeout(add, 1000);
}

$('#answer').on('click', function() {
  var countdown = document.getElementsByTagName('countdown')[0],
      start = document.getElementById('start'),
      stop = document.getElementById('stop'),
      clear = document.getElementById('clear');

  seconds = 0;
  minutes = 0;
  hours = 0;
  timer();
});
相关问题