javascript毫秒计时器_如何在倒计时器javascript中显示毫秒数

3 个答案:

答案 0 :(得分:2)

我将代码重写为包含毫秒。还要确保正确设置了setTimer。

var mins

var secs;

var ms;

function cd() {

mins = 1 * m("05"); // change minutes here

secs = 0 + s(":00"); // change seconds here (always add an additional second to your total)

ms = 0 + ms(":00");//change millisecons here

redo();

}

function m(obj) {

for(var i = 0; i < obj.length; i++) {

if(obj.substring(i, i + 1) == ":")

break;

}

return(obj.substring(0, i));

}

function s(obj) {

for(var i = 0; i < obj.length; i++) {

if(obj.substring(i, i + 1) == ":")

break;

}

return(obj.substring(i + 1, obj.length));

}

function ms(obj) {

for(var i = 0; i < obj.length; i++) {

if(obj.substring(i, i + 1) == ":")

break;

}

return(obj.substring(i + 1, obj.length));

}

function dis(mins,secs,ms) {

var disp;

if(mins <= 9) {

disp = " 0";

} else {

disp = " ";

}

disp += mins + ":";

if(secs <= 9) {

disp += "0" + secs;

} else {

disp += secs + ":";

}

if(ms <= 9) {

disp += "0" + ms;

} else {

disp += ms;

}

return(disp);

}

function redo() {

ms--;

if(ms == -1) {

ms = 99;

secs--;

}

if(secs == -1) {

secs = 59;

mins--;

}

var timerStr = dis(mins,secs,ms);

document.getElementById('countdown_fld').innerText=timerStr; // setup additional displays here.

if((mins == 0) && (secs == 0) && (ms == 0)) {

} else {

cd = setTimeout("redo()",10); //make sure to set the timer right

}

}

function init() {

cd();

}

答案 1 :(得分:2)

您使用参数1调用超时,这意味着每个计时器'事件'为1毫秒,但您在redo()函数中将该毫秒事件视为一整秒。< / p>

redo()应该是:

function redo() {

s -= 0.001; // subtract 1 millisecond

if (s < 0) {

secs = 59.999;

mins--;

}

}

等等。但是,考虑到每毫秒运行此代码会给浏览器带来相当大的负担,并且不会以精确的毫秒精度运行。您应该做的是跟踪TIME - 当您开始倒计时时,使用Date()对象记录当前系统时间,该对象具有毫秒精度。

以比毫秒(例如,每200ms / 0.2秒)更长的间隔调用你的重做(),然后从定时器的开始时间减去该点的系统时间。

答案 2 :(得分:1)

你可能感兴趣的:(javascript毫秒计时器)