2017-01-03 78 views
0

我正在寫Vue.js中的一個小遊戲,就像一個增量遊戲,而且我的定時器有問題。當用戶切換應用程序或鎖定手機時,該遊戲計劃通過Cordova定位到移動設備,timer.stop()被觸發並在頁面重新獲得焦點時恢復。 我不需要遊戲刷新很多,每秒一次或0.5 /秒就足夠了(因此速度按鈕)。Javascript定時器不同步

以下是我的問題:當我快速暫停並恢復遊戲時,計時器會失控並且進入更快的狀態,直到我暫停並重新開始計時。 Video link以獲得更好的解釋。

計時器代碼:

const {EventEmitter} = require('events') 

module.exports = class Game extends EventEmitter { 
    constructor (options = {}) { 
    super() 

    this.framesPerSecond = options.framesPerSecond || 60 
    this.maxFrameSkip = options.maxFrameSkip || 10 
    this.waitTime = options.waitTime || 0 

    this._nextTick = Date.now() 
    this._lastTick = 0 
    this._updateTicks = 0 
    this._running = false 
    } 

    get isRunning() { 
    return this._running 
    } 

    get updateTicks() { 
    return this._updateTicks 
    } 

    get currentTick() { 
    return this._updateTicks % this._framesPerSecond 
    } 

    set framesPerSecond (framesPerSecond) { 
    this._framesPerSecond = framesPerSecond 
    this._skipTicks = Math.floor(1000/framesPerSecond) 
    } 

    get framesPerSecond() { 
    return this._framesPerSecond 
    } 

    set maxFrameSkip (maxFrameSkip) { 
    this._maxFrameSkip = maxFrameSkip 
    } 

    get maxFrameSkip() { 
    return this._maxFrameSkip 
    } 

    set waitTime (waitTime) { 
    this._waitTime = waitTime 
    } 

    get waitTime() { 
    return this._waitTime 
    } 

    start() { 
    this.emit('start') 
    this._running = true 
    this._lastTick = this._nextTick 
    this._run() 
    } 

    stop() { 
    this._running = false 
    this.emit('stop') 
    } 

    _run() { 
    const next = this._nextTick = Date.now() 
    const max = this._updateTicks + this._maxFrameSkip 
    const skip = this._skipTicks 

    while (this._lastTick <= next && this._updateTicks < max) { 
     this.emit('update') 
     this._lastTick += skip 
     this._updateTicks++ 
    } 

    this._running && setTimeout(() => this._run(), this._waitTime) 
    } 
} 

我在做什麼錯誤或我還能有什麼改進?

+0

我想'this._running &&的setTimeout(()=> this._run(),this._waitTime)'將設置定時器,並且一定量的時間,它會調用'()之後=> this._run ()'當調用停止功能時,應該清除該定時器的引用。像[this](http://www.w3schools.com/jsref/met_win_cleartimeout.asp) – sandyJoshi

+0

似乎有效!把你的評論放在答案中,我可以接受它,謝謝! –

回答

1

運行計時器時,您在一定的時間間隔後調用_run。在暫停遊戲時,您並未清除該計時器。它可以使_run函數在您立即點擊按鈕時再運行一次。如下所述,您可以使用clearTimeout

// while pausing the timer, clears old timer reference 
stop() { 
    this._running = false 
    this.emit('stop') 
    if (this._timer) { 
     clearTimeout(this._timer); 
    } 
} 

_run() { 
    // All your code related to game. 

    // Here saving reference of timer in this._timer 
    if (this._running) { 
     this._timer = setTimeout(() => this._run(), this._waitTime) 
    } 
}