javascript - 游戏计时器(开始、暂停、停止)

标签 javascript jquery timer

我有一个计时器,它会在游戏开始时启动。

我需要弄清楚如何在游戏结束时停止计时器,然后返回值(已经过去的时间)

这是我的计时器:

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/

相关文章:

javascript - 在 jquery 中/使用 jquery 更改元素/类

javascript - 告诉 typescript 不要将 ["default' ] 添加到新类

php - 从数据库中获取更多数据

javascript - 检查所有下拉列表是否为空 jQuery

javascript - 我如何搜索我的函数的名称?

jquery - 淡入淡出图像?

java - Spring Quartz 计划任务在一段时间后停止运行

java - GIF 在游戏鼠标移动时停止动画

java - 为什么 Observable 类中的方法是同步的?

javascript - angularJS中$http(req)中的return语句和defer.resolve有什么区别