Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look At Loop Conditions

Why does it say "your code took too long to run?"

I am trying to do the while loop objective in this lesson and instead of helping/correcting the computer just keeps saying my code took too long to run.

Why is this happening?

app.js
var secret = prompt("What is the secret password?");
var answer;
while(answer !== "sesame"){
  alert(secret);
}

document.write("You know the secret password. Welcome.");
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>

1 Answer

lucia Antonow
lucia Antonow
7,913 Points

This means your while loop is repeating infinitely, so at a certain point the computer just stops running it. That's why it says your code took too long to run.

The reason why the loop is never ending is because answer will never equal "sesame". The reason why answer will never equal "sesame" is because you are saving the user response to secret in the line:

var secret = prompt("What is the secret password?");

Secret is set to the user response but answer is never set to anything. What you can do is:

var answer = prompt("What is the secret password?");

But you will also have to copy this code inside the loop because otherwise the user will only get one chance to answer the question and then the never ending loop will start because answer = "some wrong answer" and never = "sesame" unless you ask them to try again inside the loop.