游戏计时器(开始,暂停,停止)

时间:2012-03-19 11:47:49

标签: 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 

关于我如何实现这样的事情的任何想法?

谢谢,

3 个答案:

答案 0 :(得分:2)

也许你想要这样的东西:

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

答案 1 :(得分:0)

按照启动方式停止计时器。什么是触发器?计时器启动的是什么事件?

答案 2 :(得分:0)

使用:

Function.prototype.scope = function(context) {
    var f = this;
    return function() {
        return f.apply(context, arguments);
    };
};

Timer = function() {
    this.tick = 0;
    this.intervalId = null;
    this.period = 1000; // in ms
    this.isPaused = false;
};

jQuery.extend(Timer.prototype, {

    onTick: function() {
        if (!this.isPaused) {
            this.tick++;
        }
    },

    start: function() {
        this.intervalId = setInterval(function() {this.onTick()}.scope(this), this.period);
    },

    pause: function() {
        this.isPaused = !this.isPaused;
    },

    stop: function() {
        clearInterval(this.intervalId);

        var result = this.tick;
        this.tick = 0;
        this.isPaused = false;

        return result;
    }
});

t = new Timer();
t.start();
t.pause();
t.stop();