Javascript setTimeout的执行速度比同步setInterval快
因此,在我正在做的这个点击计时器中,我有一个Javascript setTimeout的执行速度比同步setInterval快,javascript,Javascript,因此,在我正在做的这个点击计时器中,我有一个setInterval和一个setTimeout同时运行:用户输入他/她希望游戏运行的指定秒数,然后计算你完成了多少次点击,每次点击之间的平均时间是多少,以及在指定时间段内每秒的平均点击量 <html> <head></head> <body> <input type='text' id='timerInput'></input> &
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>
点击
之前的var;
var现在;
var=0;
var-cts=0//代表“点击这一秒”
var interval=新数组();
var cps=新数组();
var计数器;
无功定时器;
var canContinue=true;
var timerInput=document.getElementById('timerInput');
var-timerTime;
var wasBad=假;
document.getElementById('btn')。onclick=function(){
如果(可以继续){
如果(单击
我有一个setInterval和一个setTimeout同时运行
这永远不会发生,因为javascript是一种单线程语言。无论代码中包含什么,javascript都不能同时执行两个命令
还有一点:
不保证计时器延迟。浏览器中的JavaScript在
单线程异步事件(如鼠标单击和计时器)
仅在执行过程中出现空缺时运行
阅读了解javascript计时器的工作原理。您设置的超时时间和间隔时间都不是保证时间。您只需告诉浏览器,它应该至少等待该时间,然后尽快调用您的回调。