Search code examples
javascriptloopsif-statementbrowserprompt

Why is function not executed when webpage is opened in browser?


I am trying to create a function that loops infinitely until user inputs that they would like to exit. Every time I open up the webpage in the browser, however, no prompt box appears and the infiniteLoop() function does not execute. Why is the infiniteLoop() function not being called?

function infiniteLoop() {
    i= 0;
    var begin= prompt("Shall we begin?");
    if (begin == "Yes") {
        var tryAgain= prompt("Exit loop?");
        if (tryAgain != "Yes") {
            infiniteLoop();
        }
    }
}

Solution

  • You need to call the function in the window onload event.

    window.onload = function(){
         infiniteLoop();
    }
    

    or, if you're using jquery

    $(function() {
        infiniteLoop();
    });