Hi I'm trying to create a simple countdown.
Here is my code but it's not working.
Can you help me find the problem?
function count() {
for (var cc=20,cc > 0,cc--) {
document.getElementById("cco").innerHTML=cc;
}
}
count();
You're using commas instead of semicolons.
for (var cc=20,cc > 0,cc--)
should be
for (var cc=20;cc > 0;cc--)
However, this probably won't do what you think it will, as the loop will count all the way to 0 immediately (so the user won't even see the countdown). I'm guessing you wanted something like:
var cc = 20;
var interval = setInterval(function()
{
document.getElementById("cco").innerHTML = -- cc;
if (cc == 0)
clearInterval(interval);
}, 1000);
See setInterval and clearInterval for more information.
There are (at least) two mistakes.
The first is syntactical: In a for loop the parameters are separated by ; and not by ,. Syntactic correct code would look like this:
function count() {
for (var cc=20;cc > 0;cc--) {
document.getElementById("cco").innerHTML=cc;
}
}
Second, you do not have a countdown, but override the very same element over and over again, without any time for the user to see the result.
A better approach would be to use setTimeout() here, which could look like this:
var cc = 20;
function count() {
document.getElementById("cco").innerHTML=cc;
if ( cc > 0 ) {
setTimeout( count, 1000 );
}
}
setTimeout( count, 1000 );
The setTimeout() approach leaves some time for the browser to actually render your modifications (and for the user to see it).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With