1
votes

I have a timer that starts when the game starts.

I need to figure out how to stop the timer when the game is over and then return the value (time that has elapsed)

Here is the timer I have:

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++;

        }
    }

 }
}

Here is how I vision the functions working:

gameTimer(start); // start timer
gameTimer(pause); // pause timer in case user needs to step away
gameTimer(stop); // stop timer and return value 

Any ideas on how I would get something like this implemented?

Thanks,

3

3 Answers

2
votes

Maybe u want something like this:

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);
}

As u can see from the code u can use the method "clearInterval(nameOfTheTimer)" to pause the interval, if u want to reset it u have to reset the timer variable. Hope it will help! :D

0
votes

Use that:

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();
0
votes

Stop the Timer the way you started it. What is the trigger? On what event the timer started?