ay2969
ay2969

Reputation: 11

Having trouble with continue/breaks in javascript

So I'm currently a novice programmer writing in javascript, and I'm having trouble understand why my continue/break statements aren't working in my code. I appreciate any help, thanks!

document.getElementById("start").onclick = function(){
    for (var i = 0; i < myArray.length; i++){
        var x = Math.random();
        x = 6*x;
        x = Math.floor(x);

        document.getElementById("question").innerHTML = myArray[x];
        document.getElementById("start").innerHTML = "Enter";   
        document.getElementById("start").onclick=function(){
            if (document.getElementById("text").value==aArray[x]){
                document.getElementById("question").innerHTML = "You are correct!";
                countPoints++;
                document.getElementById("count").innerHTML = countPoints;
                document.getElementById("start").innerHTML = "Next";
                document.getElementById("start").onclick = function(){
                    continue;
                }
            } else {
                document.getElementById("question").innerHTML = "Wrong! Gameover!";
                break;
            }
        }
    }
}

Upvotes: 0

Views: 63

Answers (1)

Marc B
Marc B

Reputation: 360702

Your break/continue are inside child functions. break/continue only apply to loops at the SAME code level, but since you're executing them inside sub-functions where there are no loops, there's nothing to break/continue, and they're effectively "do nothing" statements.

in more detail:

document.getElementBy("start").onclick = function()  {.... break; ...}

only DEFINES a function which contains a break. The function will not execute until the start element is clicked on, at which time your for loop isn't even running anymore.

It's like putting a "meet me for lunch on dec 10th" note inside a christmas present, and then wondering why no one showed up on the 10th - well, they didn't get the note until the 25th.

Upvotes: 2

Related Questions