2012-03-19 69 views
1

我有一個計時器,開始時,遊戲開始。遊戲計時器(開始,暫停,停止)

我需要弄清楚如何停止計時器,當遊戲結束,然後返回值(時間已經過去)

這裏是計時器我有:

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 

關於如何得到像這樣的東西的任何想法實現?

謝謝,

回答

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

爲u從代碼ü可以使用的方法「clearInterval(nameOfTheTimer)」看到暫停的時間間隔,如果u想重置它u必須重置計時器變量。 希望它會有所幫助! :d

+0

謝謝,哪裏的時間增量走?時間++; ? – 2012-03-19 13:31:15

+0

你可以把時間增量放在你的函數「callTimer」中,你必須在某個地方定義這個函數......我的例子是一個簡單的例子,你也許應該建立一些更加堅硬和堅實的東西,注意範圍! – cl0udw4lk3r 2012-03-19 14:11:07

+0

好吧,我明白你在說什麼。謝謝 – 2012-03-19 15:33:23