所以,我有一个setInterval
和一个setTimeout
同时运行在我正在做的这个点击计时器中:用户输入他/她希望游戏运行的指定秒数,然后它会计算你已经点击了多少次,每次点击之间的平均时间,以及你在指定时间段内每秒的平均点击量。
<html>
<head></head>
<body>
<input type='text' id='timerInput'></input>
<button id='btn'>Click</button>
<script>
var before;
var now;
var clicks = 0;
var cts = 0; //Stands for 'Clicks This Second'
var intervals = new Array();
var cps = new Array();
var cpsCounter;
var timer;
var canContinue = true;
var timerInput = document.getElementById('timerInput');
var timerTime;
var wasBad = false;
document.getElementById('btn').onclick = function() {
if(canContinue) {
if(clicks <= 0) {
if(timerInput.value.replace(/\D/, '') === timerInput.value) {
wasBad = false;
timerTime = parseInt(timerInput.value.replace(/\D/, '')) * 1000;
before = new Date();
cpsCounter = window.setInterval(ctsFunction, 1000);
timer = window.setTimeout(finish, timerTime);
}else{
alert('Only numbers please!');
wasBad = true;
}
}else{
now = new Date();
console.log(now - before);
intervals.push(now - before);
before = new Date();
}
if(!wasBad){
clicks++;
cts++;
}
}else{console.log('Game ended');}
};
function ctsFunction() {
console.log('Clicks this second: ' + cts);
cps.push(cts);
cts = 0;
}
function finish() {
console.log('Clicks: ' + clicks);
console.log('Average Speed (ms): ' + Math.floor(intervals.reduce(function(a, b){return a + b;}) / (clicks - 1)));
console.log('Average Speed (clicks per second): ' + (cps.reduce(function(a, b){return a + b;}) / cps.length));
intervals = new Array();
console.log('cps.length: ' + cps.length);
cps = new Array();
clicks = 0;
cts = 0;
window.clearInterval(cpsCounter);
canContinue = false;
}
</script>
</body>
</html>
因此,问题是,当gmae结束时,即当timer
到达末尾时,ctsFunction()
应该在最后一秒再次运行,以便它可以注册其中的数据;但是finish()
执行得更快,或者在ctsFunction()
之前执行,因此清除了cpsCounter
间隔,并且不允许它在最后一秒执行任何操作。我已经尝试在timer
中添加一些额外的毫秒,但是如果你选择运行游戏足够的秒数,同样的问题最终会发生(例如,如果你添加1ms,问题将在2秒内得到解决,但不会更多)。
发布于 2014-01-13 05:59:31
我同时运行一个setInterval和一个setTimeout
这永远不会发生,因为javascript是单线程语言。无论你的代码中有什么,javascript都不能同时执行两个命令。
还有一个:
不保证
计时器延迟。浏览器中的JavaScript在单线程上执行,异步事件(例如鼠标单击和计时器)只有在执行打开时才会运行。
阅读this article以了解javascript计时器是如何工作的。
https://stackoverflow.com/questions/21084640
复制相似问题