tags:

views:

138

answers:

4
<script type="text/javascript">
    for (count = 0; count < 10; count--) {
        alert('Dont touch this');
        count = 5;
    }
</script>
+2  A: 

It works very well. And it is an infinite loop. Count will always be less than 10, since you assign 5 to it in each iteration.

Aviator
...did you mean infinite?
froadie
@froadie: yeah:) i meant that. Edited it. Thanks!
Aviator
+5  A: 

The one thing that stands out is that count is always going to be < 10 since you are doing count--

for (count = 0; count < 10; count++)

and then remove the count = 5; and the message box should show up 10 times

JDMX
Edited: to add code formatting to code bits.
Ninefingers
+2  A: 

Try this:

for(var count = 0; count < 10; count++) {
    alert("Don't touch this");
    //Some other code
}

Your code has the variable count decrementing every time, which (assuming it would run) would result in an infinite loop.

Also, you'll want to put that in a function if it's not already, and initiate it using a button click event or some such mechanism:

function MyFunction(){
    //your code
}
Pwninstein
+4  A: 

I'm getting you are saying it doesn't work because it always repeats itself? Here is what your code is doing right now...

  • Enter For Loop
  • Set count to 0
  • Is count smaller then 10? Yes (0 < 10), continue

  • Show alert Don't touch this

  • Set count to 5
  • Decrement count by 1 (count is now 4)
  • Is count smaller then 10? Yes (4 < 10), continue

  • Show alert Don't touch this

  • Set count to 5
  • Decrement count by 1 (count is now 4)
  • Is count smaller then 10? Yes (4 < 10), continue

  • ...

Basically, you are running what is called an infinite loop, where the condition use to stay in the loop is always true.

If you are trying to show an alert only 10 times, use the following:

for(count = 0; count < 10; count++) {
    alert("Don't touch this");
}
  • count++ is incrementing count one on each iteration (you were decrementing count before)
  • Do not set the value of count on each iteration.
Andrew Moore