Javascript infinite loop in prompt

So i have just made a simple HTML page in which a JS script runs when the page loads. But the problem is that it just goes infinite after asking password. I tried to find some solutions but failed to do the same. Please help. Below is the code.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alert test</title>
</head>
<body onload="alert()">
<script>
    function alert() {
        var uname, pass, corr_uname = "admin", corr_pass = "admin";
        while(!uname) {
            uname = prompt("Enter Username: ");
        }
        while(!pass) {
            pass = prompt("Enter Password: ");
        }
        if((uname == corr_uname) && (pass == corr_pass)) {
            alert("Access Granted!!");
        } else {
            alert("Access Denied!");
            alert();
        }
    }
</script>
<h1>Welcome!</h1>
</body>
</html>

The funny thing is that when i run the same code (JS runs after clicking a button) in W3Schools, it just works fine!!

>Solution :

The problem is that you have created a function named alert which already exists in javascript, so you are calling it recursively and infinitely.

Solution fix

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alert test</title>
</head>
<body onload="alert2()">
<script>
    function alert2() {
        var uname, pass, corr_uname = "admin", corr_pass = "admin";
        while(!uname) {
            uname = prompt("Enter Username: ");
        }
        while(!pass) {
            pass = prompt("Enter Password: ");
        }
        if((uname == corr_uname) && (pass == corr_pass)) {
            alert("Access Granted!!");
        } else {
            alert("Access Denied!");
            myFunction();
        }
    }
</script>
<h1>Welcome!</h1>
</body>
</html>

I renamed your functional alert to alert2.

Kindly accept it as answer if it works for you, thanks!

Leave a Reply