I am in the process of creating a simple javascript file that counts down from 20 to 0. I am stuck on how to fix it. Here is my code, any help is really appreciated!
var count;
document.write("Starting Loop" + "<br />");
for (count = 20; count <= 0; count++) {
document.write("Current Count : " + count + "<br / >");
//document.write("<br />");
}
document.write("Loop stopped!");
I am in the process of creating a simple javascript file that counts down from 20 to 0. I am stuck on how to fix it. Here is my code, any help is really appreciated!
var count;
document.write("Starting Loop" + "<br />");
for (count = 20; count <= 0; count++) {
document.write("Current Count : " + count + "<br / >");
//document.write("<br />");
}
document.write("Loop stopped!");
Share
Improve this question
edited Oct 5, 2016 at 15:36
davidhu
10.5k7 gold badges35 silver badges57 bronze badges
asked Oct 5, 2016 at 14:57
MarieMarie
131 silver badge2 bronze badges
2
-
for(count = 20; count <= 0; count++)
. Problem 1: You're checking if count is less than or equal to zero. Problem 2: You're incrementingcount
– j08691 Commented Oct 5, 2016 at 14:59 - You're looking to count down. What are you doing to the count variable in your for-loop? – Chris Forrence Commented Oct 5, 2016 at 14:59
3 Answers
Reset to default 4The three clauses in a for-loop tell the following thing (in order):
- What are the initial values?
- How long do I keep going?
- What do I change each iteration?
In your particular case, you're starting the count at 20, you're continuing in the loop as long as the count is less than or equal to 0, and you're adding 1 to the count each time it loops. Since the second clause evaluates to false, the for-loop won't run!
What you are looking for should be more like this:
for (count = 20; count >= 0; count--)
This will start the count at 20, continue as long as the count is greater than or equal to 0, and subtract 1 from the count on each iteration.
Putting it all together...
var count;
document.write("Starting Loop" + "<br />");
for (count = 20; count >= 0; count--) {
document.write("Current Count : " + count + "<br / >");
}
document.write("Loop stopped!");
You can use setTimeout
and recursive function.
setTimeout
take two parameter, the function executed and the time in ms before execution. Here you can choose the delay between each iteration.
var counter=20;
function countdown(counter)
{
if(counter>0)
{
counter--;
setTimeout(function(){countdown(counter)},1000);
console.log(counter);
}
}
countdown(counter);
You issue is the counter is wrong. You have
for(count = 20; count <= 0; count++)
This is saying start at count = 20
, until count is less or equal to zero, add 1 to count each time. That does not make any sense.
Here's what you should use.
document.write("Starting Loop" + "<br />");
for (var count = 20; count >= 0; count--) {
document.write("Current Count : " + count + "<br / >");
//document.write("<br />");
}
document.write("Loop stopped!");