illegal use of break statement; javascript

lehermj picture lehermj · Mar 21, 2014 · Viewed 103k times · Source

When this variable becomes a certain amount i want the loop to stop, but i keep getting the error, "Uncaught SyntaxError: Illegal break statement".

function loop() {
    if (isPlaying) {
        jet1.draw();
        drawAllEnemies();
        requestAnimFrame(loop);
        if (game==1) {

            break;

        }

    }
} 

Answer

Arun P Johny picture Arun P Johny · Mar 21, 2014

break is to break out of a loop like for, while, switch etc which you don't have here, you need to use return to break the execution flow of the current function and return to the caller.

function loop() {
    if (isPlaying) {
        jet1.draw();
        drawAllEnemies();
        requestAnimFrame(loop);
        if (game == 1) {
           return
        }
    }
}

Note: This does not cover the logic behind the if condition or when to return from the method, for that we need to have more context regarding the drawAllEnemies and requestAnimFrame method as well as how game value is updated