Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!