Helmet_Gaming
Helmet_Gaming

Reputation: 57

How do I brake While-Loop with a function defined before?(plain Java Script)

I´m about to create a simple game, but the game-loop isn´t working yet. The while-loop does not break ,if I call the end_game function and keeps printing 'a'. I realy could not figure out what´s wrong with it. Thank you guys.

var game_status = true;

var end_game = function end_game(){
                    game_status = false;
                    return game_status;
                    };

var game_loop = function game_loop(game_status, end_game){
                  while(game_status == true){
                        console.log('a');
                        end_game();
                  }
              };

function call_gameloop(){
    game_loop(game_status,end_game);
};
<div id = 'play_field' onclick='call_gameloop();'></div>

Upvotes: 0

Views: 88

Answers (1)

Vaibhav Nigam
Vaibhav Nigam

Reputation: 1467

game_status variable in game_loop() function is local to the function and is different from the globally declared variable.

end_game() function modifies global variable and therefore does not break the above loop.

To make things work, don't pass game_status parameter to game_loop() function like you didn't pass to end_game() function.

Upvotes: 1

Related Questions