Search code examples
google-api-javascript-client

Is there any code to simply restart my whole function?


I started learning Google Javascript on my own, and as my first code is to do an interactive calculator which the equation can be selected by pressing some images of those equations. The problem is I want to repeat the function when unintended info is entered, it will say please try again and restart the code. What should I write at the end of the code?

else{
    Browser.msgBox("XXXXXXXXXXXXX");
    / *enter the loop code here*

Solution

  • A good way is to set a variable to null, and then use a while-loop It is also good to separate out the code which controls the user interface (in your example, a message box), and the code that validates the input

    function validate_input(user_input){
        if(...your code here...)
        {
            //user input is valid
            return true;
        }else{
            //user input is invalid
            return false;
        }
    }
    
    var user_input = null;
    
    //it is necessary to use triple equals to compare to null
    while(user_input===null){
    
        user_input=get_user_input_somehow(); //you specify 
        if(validate_input(user_input)){
    
        //do nothing
        }
        else{
    
        Browser.msgBox("xxxxxxx");
    
        //this line is very necessary
        //if the input is invalid, reset the input to null
            user_input = null;
    
        }
    }
    
    //by this point in the code, the user_inut is assured to be valid
    //otherwise the loop would still be running