谁能告诉我,我做错了什么?我有一个计时器,它一次显示2或3或4秒,而不是每秒。
var call_s = 0;
var call_m = 0;
var call_h = 0;
var call_connected = null;
var display = null ;
function connected_timer_start(tototo) {
call_connected = setTimeout(function() {
call_s++;
if (call_s>59) {
call_s = 0;
call_m++;
}
if (call_m>59){
call_m = 0;
call_h++;
}
display = (call_h < 10 ? '0' : '') + call_h + ':' +
(call_m < 10 ? '0' : '') + call_m + ':' +
(call_s < 10 ? '0' : '') + call_s;
console.log(display);
connected_timer_start();
}, 1000);
}
function connected_timer_stop() {
call_s = 0;
call_m = 0;
call_h = 0;
clearTimeout(call_connected);
call_connected = null;
document.getElementById('display').style.display = 'none';
}
答案 0 :(得分:2)
正如jfriend00所说,你不应该使用setTimeout()
来计算时间值,因为它不可靠。使用Date()
的代码版本实际上更短更简单:
var begining_timestamp = null;
var call_connected = null;
var call_ms = null;
var display = null ;
function connected_timer_start() {
if (call_connected==null) {
begining_timestamp = (new Date()).getTime();
count();
} else {
console.log('One timer is already started!');
}
}
function count() {
call_connected = setTimeout(function() {
getCallLength();
count();
}, 1000);
}
function getCallLength() {
call_ms = (new Date()).getTime() - begining_timestamp;
var tmp_date = new Date(null);
tmp_date.setSeconds(call_ms/1000);
display = tmp_date.toISOString().substr(11, 8);
console.log(display);
}
function connected_timer_stop() {
clearTimeout(call_connected);
getCallLength();
call_connected = null;
document.getElementById('display').style.display = 'none';
}
我认为这种方法有几个好处:
call_ms
变量不会被清除,但是当呼叫开始时;这意味着在两次调用之间,您始终可以使用以毫秒为单位的最后一个调用长度connected_timer_start
现在检查计时器是否尚未启动