
在 phaser 3 游戏开发中,使用 `setinterval` 触发 ajax 请求更新全局变量时,常因 javascript 异步执行机制导致变量“看似未更新”——实际是读取过早,而非赋值失败。
你遇到的问题本质是时序(timing)与异步(asynchrony)的误解,而非作用域或声明问题。虽然 player1type 是全局变量,但 console.log("OUTSIDE INTERVAL: "+player1type); 在 create() 函数末尾立即执行,此时 setInterval 的第一次回调尚未触发(需等待整整 1 秒),更不用说 AJAX 请求的发送、响应和解析——整个链路都是异步延迟的。因此,该日志必然输出 undefined。
✅ 正确做法不是“让外部等待”,而是主动设计状态响应机制。以下是优化后的专业实践:
1. 使用 async/await + fetch(推荐替代 jQuery.ajax)
// 全局声明(建议用 let/const 替代 var,更语义化)
let player1type = null;
async function fetchWaitingRoomData() {
try {
const response = await fetch('../includes/waitingroomcheck.php', {
method: 'GET',
cache: 'no-cache'
});
const result = await response.text();
const data = JSON.parse(result);
player1type = data.player1type ?? null;
console.log('✅ Updated player1type:', player1type);
return data;
} catch (error) {
console.error('❌ Failed to fetch waiting room data:', error);
return null;
}
}
create() {
// 启动轮询:首次立即执行,之后每秒一次
const poll = async () => {
await fetchWaitingRoomData();
setTimeout(poll, 1000); // 比 setInterval 更可控,避免累积延迟
};
poll(); // 立即触发首次请求
// ✅ 此处不应依赖 player1type 的初始值
// 而应在数据就绪后触发逻辑(见下文)
}2. 响应式数据更新:监听变化而非轮询读取
// 封装状态管理,支持订阅
class PlayerState {
#value = null;
#subscribers = new Set();
get type() { return this.#value; }
set type(value) {
if (this.#value !== value) {
this.#value = value;
this.#subscribers.forEach(cb => cb(value));
}
}
subscribe(callback) {
this.#subscribers.add(callback);
return () => this.#subscribers.delete(callback);
}
}
const playerState = new PlayerState();
// 在 fetch 成功后更新
playerState.type = data.player1type;
// 在任意需要响应的地方订阅
playerState.subscribe((type) => {
if (type === 'user') {
// ? 这里才是安全使用 player1type 的位置
this.scene.start('GameScene');
}
});⚠️ 关键注意事项:
- ❌ 避免在 setInterval 外部直接读取异步更新的变量值——它永远“来不及”;
- ✅ 所有依赖该变量的逻辑,必须放在成功回调、then()、await 后或状态订阅中;
- ✅ 使用 setTimeout 递归替代 setInterval,可防止请求堆积(如网络延迟导致多次并发请求);
- ✅ 总是处理 JSON 解析异常和网络错误,避免静默失败;
- ✅ Phaser 3 推荐使用原生 fetch 或 axios,jQuery.ajax 已非现代最佳实践。
通过将“轮询”升级为“响应式状态管理”,你的游戏逻辑将更健壮、可测且符合前端工程规范。










