I am building a game with Phaser 3. I have an ajax call I want to make every second to get player data like so:
//Var is globally declared
var player1type;
create() {
setInterval(function() {
function gameWaitingroom(getWaitingroom) {
$.ajax({
type: "GET",
url: '../includes/waitingroomcheck.php',
cache: false,
success: getWaitingroom
});
}
// resolve/success callback
gameWaitingroom(result => {
try {
var waitingRoomData = JSON.parse(result);
}
catch (error) {
console.log('Error parsing JSON:', error, result);
}
//status = waitingRoomData.statusCode;
player1type = waitingRoomData.player1type;
console.log("INSIDE INTERVAL: " player1type);
});
},1000);
console.log("OUTSIDE INTERVAL: " player1type);
}
My console reads like so:
INSIDE INTERVAL: user
OUTSIDE INTERVAL: undefined
Why is var player1type undefined outside of the setInterval, but it works inside just fine, even though I’ve globally declared it?
CodePudding user response:
That's because when the script first run the code in setInterval() will take 1s to be executed whiles the one outside it will be executed instantly. So by the time console.log("OUTSIDE INTERVAL: " player1type); get executed, its value will be undefined that's because player1type = waitingRoomData.player1type; will still be waiting for 1s to be executed.
