我有一个计时器,它会在游戏开始时启动。
我需要弄清楚如何在游戏结束时停止计时器,然后返回值(已经过去的时间)
这是我的计时器:
function gameTimer(status) {
$(".notes").text(status);
if (gameStart == true) {
gameStart = false; // so game will not repeat when image is clicked again to start game
var timer = setInterval(calltimer, 1000);
function calltimer() {
$(".timerInner").text(time);
if (status == true) {
time++;
}
}
}
}
以下是我对函数工作的看法:
gameTimer(start); // start timer
gameTimer(pause); // pause timer in case user needs to step away
gameTimer(stop); // stop timer and return value
关于如何实现这样的东西有什么想法吗?
谢谢,
最佳答案
也许你想要这样的东西:
var gameStart = false;
function gameTimer (status) {
switch (status) {
case "start":
if (gameStart === false) {
var timer = setInterval(callTimer, 1000);
gameStart = true;
}
break;
case "pause":
if (gameStart === true && timer !== null) {
clearInterval(timer);
gameStart = false;
}
break;
case "continue":
if (gameStart === false && timer !== undefined && timer !== null) {
timer = setInterval(callTimer, 1000);
gameStart = true;
}
break;
case "stop":
if (timer !== null) {
timer = null;
gameStart = false;
}
break;
}
$(".notes").text(status);
}
正如您从代码中看到的那样,您可以使用方法“clearInterval(nameOfTheTimer)”来暂停间隔,如果您想重置它,则必须重置计时器变量。 希望它会有所帮助! :D
关于javascript - 游戏计时器(开始、暂停、停止),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9769585/