Javascript break/continue statement

1k views Asked by At

I can't get this working:

var x = 1;

while (x == 1) {
}

function changeX(val) {
     if (val == 1) {
          x = 1;
     } else if (val == 0) {
          x = 0;
          break;
     }
}

and no matter what I do, I can't get this working. What I want to do is: I want the loop to stop working when I choose "0" or type it or anything. I have to use break/continue .

No matter what I do, I get wrong use of break or my browser crashes.

PS. In HTML part I put

<input type="text" value="1" onchange="changeX(this.value)">
2

There are 2 answers

0
Jonas Wilms On BEST ANSWER

Making your code work:

While will block the browsers thread. Therefore, you cannot click. Do:

var x=false;
function react(){
     if(x){return;}
    //your code
    console.log("sth");//e.g.
    setTimeout(react,0);
}
react();

Now you can do your UI stuff

function changeX(val) { 
    if (val == 0) { 
        x = true;
    }
}

What you really want:

var timer=false;

function input(val){
    if(timer){
        clearInterval(timer);
        timer=false;
    }
    if(val){
        timer=setInterval(function(){
        val++;
        alert(val);

        if(val==10){
            clearInterval(timer);
            timer=false;
        }
    }, 1000);
}

<input oninput="input(this.value)">
0
Force Bolt On
 <h3>Break Statement</h3>
   <script>
        let num=0;
        while(num<5){
            num++;
            if((num==3)){
                break;
            }else{
                document.write("num is: "+num+"<BR/>")
            }
        }
        document.write("When if condition is true: while Loop Terminated");
    </script>


 <h3>Continue Statement</h3>
    <script>
        let val=0;
        while(val<5){
            val++;
            if(val==3){
                // skip the current loop iteration and jump to the next iteration
                continue;
            }
            document.write("val = "+val+"<BR/>");
        }
    </script>