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 Create a while Loop

Bakari Lewis
Bakari Lewis
6,556 Points

Need help...Why is it saying "Your code took too long to run"

Not sure how to make this code run faster. Or are there any errors in this code?

Thanks for the help :)

script.js
var count = 0;
while (count<27){
  var count =+ 1;
  document.write(count);
}

2 Answers

I think you've redefined the variable count by calling it var a second time. I also think that =+ isn't incrementing your variable so the loop is carrying on forever as it'll never reach the escape value.

Have a look at this and see if it makes sense:

var count = 0;

while (count < 26) {
  document.write(count);
  count++;
}  

I hope that helps.

Steve.

I think in your code, the second definition of var count is out of scope to the while control loop. So, your first count variable, defined outside of the loop, stays at zero whilst the one inside does whatever it does but isn't controlling the loop. You've redefined a new variable inside the loop that's getting =+ applied to it - and I'm not sure =+ right - but the scope issue looks to be the reason the code will run forever - there's nothing incrementing the first count.

Steve.

Bakari Lewis
Bakari Lewis
6,556 Points

Thanks! this worked!

Count need to be incremented using += or ++ not by using =+. When it says that it is taking to long to run, it usually means that your loop is incomplete, meaning that it is not being changed in any way, or that it has some sort of syntax error causing it to be an infinite loop going on forever and it could eventually crash your browser. Hope this helps!

Quick code example:

var count = 0;
while (count<27){
  var count += 1; //you can also use 'count++;' to increment it by one
  document.write(count);
}
Bakari Lewis
Bakari Lewis
6,556 Points

That makes sense now! Thanks a lot. :)

Glad to help!