You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Phaser的update()方法中按条件执行延迟重复的JS函数?

问题原因

Phaser 场景的update()生命周期方法每帧都会触发一次,常规运行帧率为60帧/秒,约16ms执行一次。你当前的写法会在isPlaying为true时,每帧都新增一个2500ms延迟的循环定时事件,运行几秒后就会累积上百个待触发的createItem任务,最终呈现出函数执行频率和帧率同步、无延迟效果的现象。

修复方案

方案1:加标记位控制事件仅创建一次

适合需要动态创建/销毁定时事件的场景,通过额外标记位避免重复添加事件:

// 在场景的create()生命周期中初始化标记位
create() {
  // 标记是否已经添加了生成道具的定时事件
  this.itemEventInited = false
  // 其余原有逻辑
}

update(){
  // 仅在isPlaying为true、且未创建过事件时添加一次
  if(isPlaying && !this.itemEventInited){
    this.time.addEvent({
      delay: 2500, 
      callback: createItem, 
      callbackScope: this, 
      loop: true
    }); 
    this.itemEventInited = true
  }
  // 如果需要支持isPlaying切换为false时停止事件,补充以下逻辑
  if(!isPlaying && this.itemEventInited) {
    this.time.removeAllEvents()
    // 也可以将事件实例存起来单独销毁,避免影响其他定时任务
    this.itemEventInited = false
  }
}

方案2:提前创建事件,用暂停属性控制启停

更推荐的写法,避免反复创建销毁事件带来的性能损耗:

// 在场景的create()生命周期中提前创建好定时事件,初始设为暂停状态
create() {
  this.itemCreateEvent = this.time.addEvent({
    delay: 2500, 
    callback: createItem, 
    callbackScope: this, 
    loop: true,
    paused: true
  })
  // 其余原有逻辑
}

update(){
  // 直接根据isPlaying状态控制事件是否暂停即可
  this.itemCreateEvent.paused = !isPlaying
}
注意事项

建议将全局变量isPlaying改为挂载到场景实例上的属性,避免全局变量污染导致的状态判断异常。

内容的提问来源于stack exchange,提问作者Likas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 20:06:08