首页 > 解决方案 > 如何只触发一次增量

问题描述

我已经使用了这个setTimeout函数,所以我的对象会保持y<0一段时间,当时我希望我的增量只触发一次,但它会继续触发......更多我使用setTimeout函数延迟我的函数,增量操作被触发的次数更高。 .....那么,无论我的对象停留多长时间,我的增量仅触发一次的解决方案是什么y<0

Player.prototype.checkInWater = function () {
     if (this.y < 0) {
       ++scoreGot
       setTimeout(function(){  
         player.x = 202;
         nplayer.y = 405;
       }, 300);
    }
};

标签: javascript

解决方案


Player = function(){
     ....
     this.checkedInWater = false;
}
Player.prototype.checkInWater = function () {
     if (this.y < 0 && !this.checkedInWater) {
       ++scoreGot;
       t = this;
       t.checkedInWater = true;

       setTimeout(function(){  
         player.x = 202;
         nplayer.y = 405;
         t.checkedInWater = false;
       }, 300);
    }
};

推荐阅读