Javascript构造函数:如何查找计时器是否达到零?

时间:2016-01-25 15:39:18

标签: javascript

function MyGame() {
   var declaration
}
MyGame.prototype.initialize() {
   //methods and variable initialize
}
//other logics  

我还没有完成这个脚本。所以我只是输入它的外观。

countdown.js看起来像这样。

"use strict"

function Countdown() {
    this.seconds = 10;
    this.interval = null;
}

Countdown.prototype.startCountdown = function() {

var self = this;
this.renderTimer();
this.interval = setInterval(function() {

        if(!self.isNegative()) {
            self.seconds = self.seconds - 1;
            self.renderTimer();
        }
    }, 1000);
}

Countdown.prototype.isNegative = function() {
if(this.seconds <= 0) {
    return true;
    this.cancelInterval();
}
return false;
}

在那个游戏javascript文件中,我是否需要编写另一个超时函数来读取倒数计时器的值?

MyGame.prototype.checkgameOver = function() {

    var interval;
    var self = this;
    interval = setInterval(function() {
        if(self.timer.getSeconds() <= 0 ) {
            self.gaemOver();
            clearInterval(interval);            
        }
    }, 1000);

 }

我想在计时器为零时停止游戏 那么,我需要从倒数计时器调用gameOver函数吗? 当计时器达到零时结束游戏的最佳方法是什么?

1 个答案:

答案 0 :(得分:0)

因此,请更改运行计时器的逻辑。

this.interval = setInterval(function() {
    if(self.isNegative()) { 
        //call game over code
    } else 
        self.seconds = self.seconds - 1;
        self.renderTimer();
    }
}, 1000);
相关问题