Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading