Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

113
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda