有没有办法让您在两者之间延迟:this.bullets.push(this.ship.shoot());

时间:2019-03-30 18:50:47

标签: javascript

有没有办法在两者之间增加延迟? this.bullets.push(this.ship.shoot());

if (this.mscore >= 1000) {
  if (input.isPressed("spacebar")) {

    this.bullets.push(this.ship.shoot());
    this.bullets.push(this.ship.shoot());

  }
}

2 个答案:

答案 0 :(得分:1)

一种可能的解决方案是使用setTimeout(),在下一个示例中,大约在1000ms之后执行第二个代码:

let delay = 1000;

if (this.mscore >= 1000)
{
    if (input.isPressed("spacebar"))
    {
        this.bullets.push(this.ship.shoot());
        let that = this;

        setTimeout(
            () => that.bullets.push(that.ship.shoot()),
            delay
        );
    }
}

答案 1 :(得分:0)

您可以使用setInterval或setTimeout

下面是setInterval的示例,它将保持“拍摄”状态。

const pressed = true
let interval = null

if (pressed) {
  shoot()
  interval = setInterval(() => shoot(), 1000)
} else {
  interval = clearInterval(interval)
}

function shoot() {
  console.log('shoot')
}