Search code examples
javascripthtmlprompt

`while` loop with `prompt` is never showing any `console.log`


I was just trying to check if my console gets connected to my code, and previosly it did for the same program, but now it’s not even loading the basic HTML page which contains just the heading, and it’s not showing anything in the console. Why is it behaving like this?

Screenshot showing a prompt dialog box, but no console output and the HTML page not loaded.

var todos = [ "whats up dude!!" ];
var input = prompt("what would you like to do?");

while (input !== "quit") {
  if (input === "list") {
    todos.forEach(function(todo, i) {
      console.log(i + ": " + todo);
    });
  }
  else if (input === "new") {
    var newTodo = prompt("what do you want?");
    
    todos.push(newTodo);
  }
  else if (input === "delete") {
    var index = prompt("Enter index of todo to delete");
    
    todos.splice(index, 1);
    console.log("Todo Removed");
  }

  input = prompt("what would you like to do?");
}

console.log("You have Quit!!");
<!DOCTYPE html>
<html>

<head>
  <title>one more try</title>
  <script type="text/javascript" src="tryy.js"></script>
</head>

<body>
  <h1>its the last resort</h1>
  <h4>hope i win this!!</h4>
</body>

</html>


Solution

  • Instead of a tight loop that never yields control of the script, or page, to anything else, you can put a small delay before each prompt with setTimeout:

    var todos=["whats up dude!!"];
    
    function interactWithToDos()
    {
      var input=prompt("what would you like to do?");
      
      if(input==="list")
      {
        todos.forEach(function(todo, i)
        {
          console.log(i +": "+ todo);
        });
      }
      else if(input==="new")
      {
        var newTodo=prompt("what do you want?");
        todos.push(newTodo);
      }
      else if(input === "delete")
      {
        var index = prompt("Enter index of todo to delete");
        todos.splice(index, 1);
        console.log("Todo Removed");
      }
      
      if(input !== "quit")
      {
        setTimeout(interactWithToDos, 0);
      }
      else
      {
        console.log("You have Quit!!");
      }
    }
    
    setTimeout(interactWithToDos, 0);