<script type="text/javascript">
for (count = 0; count < 10; count--) {
alert('Dont touch this');
count = 5;
}
</script>
views:
138answers:
4It 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.
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
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
}
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
countto 0 Is
countsmaller then 10? Yes (0 < 10), continueShow alert
Don't touch this- Set
countto 5 - Decrement
countby 1 (countis now 4) Is
countsmaller then 10? Yes (4 < 10), continueShow alert
Don't touch this- Set
countto 5 - Decrement
countby 1 (countis now 4) Is
countsmaller 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 incrementingcountone on each iteration (you were decrementingcountbefore)- Do not set the value of
counton each iteration.