我正在做一些有趣的反应游戏,因为我是新手,这是一个相当大的挑战,所以,我遇到了问题,如何在按下按钮时让脚本停止运行,我已经设法在点击开始时启动所有内容,但无法停止运行。 也许任何人都有任何想法如何实现这一目标?到目前为止,这是我的代码:
这是我的HTML:
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
<p>Your reaction time: <u><span id="timeTaken"></span></u></p>
<p>Your average reaction time: <u><span id="average"></span></u></p>
<p>Your best reaction time: <u><span id="best"></span></u></p>
<div id="shape"></div>
这是我的javascript:
var start = new Date().getTime();
function getRandomColor() { //generates random color
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function makeShapeAppear() { //makes that shape appear on screen
var top = Math.random() * 400;
var left = Math.random() * 400;
var width = (Math.random() * 200) + 100;
if (Math.random() > 0.5) {
document.getElementById("shape").style.borderRadius = "50%"
} else {
document.getElementById("shape").style.borderRadius = "0";
}
document.getElementById("shape").style.backgroundColor = getRandomColor();
document.getElementById("shape").style.top = top + "px";
document.getElementById("shape").style.left = left + "px";
document.getElementById("shape").style.width = width + "px";
document.getElementById("shape").style.height = width + "px";
document.getElementById("shape").style.display = "block";
start = new Date().getTime();
}
function appearAfterDelay() { //makes that shape appear after some delay
setTimeout(makeShapeAppear, Math.random() * 3000);
}
document.getElementById("reset").onclick = function() { //reset button, so when you click it, everything resets
location.reload();
}
var totaltime = 0;
var totalgames = 0;
document.getElementById("start").onclick = function() { //start button, so when you click it, shapes start appearing and time's running
appearAfterDelay();
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.display = "none";
var end = new Date().getTime();
var timeTaken = (end - start) / 1000;
totaltime += timeTaken;
totalgames += 1;
var notroundaverage = (totaltime / totalgames);
var roundaverage = notroundaverage.toFixed(3);
document.getElementById("timeTaken").innerHTML = timeTaken + " s";
document.getElementById("average").innerHTML = roundaverage + " s";
appearAfterDelay();
}
}
答案 0 :(得分:0)
JavaScript是基于事件的,你真的不应该试图阻止&#39;它。通过查看代码,我可以看到您真正想要做的是清除单击按钮时的超时。这可以通过放置这一行来实现:
var timeOutId;
位于代码顶部,并且正在更改
setTimeout(makeShapeAppear, Math.random() * 3000);
到
timeOutId = setTimeout(makeShapeAppear, Math.random() * 3000);
然后,只需添加一个按钮,其中包含一个清除超时的点击事件,可以使用以下行来实现:window.clearTimeout(timeOutId);