我写了这段代码来计算秒数(使用 decisec 和 centisec)。
You've wasted time <span id="alltime">0.00</span> seconds.
<script type="text/javascript">
function zeroPad(num,count)
{
var numZeropad = num + '';
while(numZeropad.length < count) { numZeropad = "0" + numZeropad; }
return numZeropad; }
function counttwo() {
tall = document.getElementById('alltime').innerHTML;
if(parseFloat(tall) < 1.00) { tnew2 = tall.replace('0.0','').replace('0.',''); }
else { tnew2 = tall.replace('.',''); }
tnum = parseInt(tnew2) + 1;
//check if have to add zero
if(tnum >= 100) { tstr1 = tnum + ''; }
else { tstr1 = zeroPad(tnum,3); }
tlast = tstr1.substr(0,tstr1.length - 2) + '.' + tstr1.substr(tstr1.length - 2);
document.getElementById("alltime").innerHTML = tlast;
}
var inttwo=setInterval("counttwo()",10);
</script>
在HTML文件中运行。
它运行良好,但是当我使用 Firefox 4 并运行代码时。当它在某些数字上(随机如 12.20、4.43)时,它似乎有点滞后(在计数之前停止一点)。我试过将“counttwo()”更改为 counttwo,但这没有帮助。
我已经告诉我的一些 friend 也可以在 Firefox 4 上运行。他们说它一点也不滞后。这是因为我的电脑造成的?还是我的火狐?还是别的?
提前致谢!
附言。在这里 fiddle :http://jsfiddle.net/XvkGy/5/镜子:http://bit.ly/hjVtXS
最佳答案
当您使用 setInterval 或 setTimeout 时,由于多种原因,时间间隔并不准确。它依赖于其他运行的 javascript、浏览器、处理器等。您必须将 +- 15ms 的可靠性视为理所当然的 afaik。 See also ...
关于Firefox 中的 Javascript setinterval() 滞后?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5792187/