Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

114
Vistas
Update Global var with setInterval Not Working

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda