简体   繁体   中英

Javascript break/continue statement

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)">

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)">
 <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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM