在函数内设置定时器

时间:2013-02-27 21:47:04

标签: javascript function object timer

我有一个游戏对象,我想在一定时间后产生回来(变得活跃)。每次时间到期,我都会收到此错误:

Uncaught TypeError: Object [object global] has no method 'SpawnCounter'

不确定我做错了什么?这是我的目标的一部分:

this.Update = function(){
    //Collisions
    if(this.active){
        if(player.Intersects(this)){
            console.debug("Player Touching Pick Up!");
            if(this.type == "weapon")
                player.weapon = this.subtype;
            this.active = false;
        }
    }
    else{
        //THIS IS THE TIMER
        setTimeout( function(){ this.SpawnCounter(); }, 2000 );
    }
};

this.SpawnCounter = function(){
    this.active = true;
};

所有这一切,只是一个游戏提取 - 在2秒后重新出现。

1 个答案:

答案 0 :(得分:0)

也许尝试将此范围限定为另一个变量......

this.Update = function(){
    var that = this;
    //Collisions
    if(this.active){
        if(player.Intersects(this)){
            console.debug("Player Touching Pick Up!");
            if(this.type == "weapon")
                player.weapon = this.subtype;
            this.active = false;
        }
    } else{
        //THIS IS THE TIMER
        setTimeout( function(){ that.SpawnCounter(); }, 2000 );
    }
};

this.SpawnCounter = function(){
    this.active = true;
};