Search code examples
javascriptcontinue

How can i continue while cycle?


The user is typing his/her password until it would be correct. When user want to click "Cancel" we ask "Are you sure?" and if the answer is no, then again ask for the password.

I tried to use to strat again but it does not work =(


var password = "username",
    user_password        ,
    checked = true       ,
    user_password = prompt("Enter your password"),
    checked_confirm      ;

label: while(checked){
    if(user_password == password){
        alert("You are successfully logged in");
        break;
    }
    else if(user_password == null){
        checked_confirm =  confirm("Are you sure you want to cancel authorization?");
        if(checked_confirm){
            alert("You have canceled authorization");
            break;
        }
        else{
            continue lable;
        }
    }
    else{
        user_password = prompt("Enter your password");
    }
}


Solution

  • Ask for the password at the start of the loop, and don't break `till you get it:

    var password = "username",
      user_password,
      checked_confirm;
    
    while (true) {
      user_password = prompt("Enter your password");
    
      if (user_password == password) {
        alert("You are successfully logged in");
        break;
      } else if (user_password == null) {
        checked_confirm = confirm("Are you sure you want to cancel authorization?");
        if (checked_confirm) {
          alert("You have canceled authorization");
          break;
        }
      } else {
        alert("Wrong password");
      }
    }