我需要一个非常快的 Javascript 计时器。计时器分辨率被认为是 10 毫秒。我已经实现了一个工作计时器,但问题是,时间总是取决于浏览器中运行的其他资源的数量。当动画 GIF 运行时,我的计时器根本无法工作。这是代码(工作!):
var timer = new Timer();
function Timer(){
var time = 0;
//Every 10ms we are incrementing the timer:
setInterval(function(){
time=time+1;
},10);
this.getTime=function(){return time;}
}
function testTimer(){
var counter = 0;
var resultsum = 0;
var everytensum = 0;
setInterval(function(){
counter = counter + 1;
window.timeoutTesterRunning = true;
var timeoutTester = new TimeoutTester();
setTimeout(function(){
console.log(counter+": "+timeoutTester.getResult());
resultsum = resultsum+timeoutTester.getResult();
console.log(resultsum);
if(counter%10==0){
console.log("Counting last 10 seconds: "+(resultsum-everytensum));
console.log("Counting last "+counter+" seconds: "+resultsum);
everytensum = resultsum;
}
},1200)
}, 3000);
}
function TimeoutTester(){
var result;
var snap_time1 = timer.getTime();
setTimeout(function(){
var snap_time2 = timer.getTime();
result = snap_time2-snap_time1;
},1000);
this.getResult=function(){return result;}
}
现在来自 console.log 的结果(总和在括号中):
[10:10:54.466] 1: 100 (100)
[10:10:57.466] 2: 100 (200)
[10:11:00.466] 3: 100 (300)
[10:11:03.466] 4: 100 (400)
[10:11:06.466] 5: 100 (500)
[10:11:09.465] 6: 100 (600)
[10:11:12.466] 7: 101 (701)
[10:11:15.467] 8: 100 (801)
[10:11:18.467] 9: 100 (901)
[10:11:21.467] 10: 100 (1001)
[10:11:21.476] Counting last 10 seconds: 1001
[10:11:24.467] 11: 100 (1101)
[10:11:27.468] 12: 100 (1201)
[10:11:30.467] 13: 100 (1301)
[10:11:33.478] 14: 60 (1361) //Animated Gif started: Less countings! ("Time runs longer")
[10:11:36.476] 15: 57 (1418)
[10:11:39.482] 16: 58 (1476)
[10:11:42.472] 17: 61 (1537)
[10:11:45.474] 18: 56 (1593)
[10:11:48.484] 19: 48 (1641)
[10:11:51.470] 20: 55 (1696)
[10:11:51.476] Counting last 10 seconds: 695
[10:11:51.482] Counting last 20 seconds: 1696
柜台运行很规律。但是当浏览器忙时(通过动画 GIF),Javascript 没有时间正确设置间隔。该函数Timer()
只是没有收到它需要增加的时间var time
,所以值太低了(当我第一次开始测试时,值甚至更低,约为 40,但我能够通过使用函数将它们提高到 ~55执行)。
任何人都知道我们如何让 Javascript 计时器工作?还是无法阻止浏览器杀死计时器?