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();
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).
Change ',' with ';' in your for loop
function count() {
for (var cc=20;cc > 0;cc--) {
document.getElementById("cco").innerHTML=cc
}
}
count();
Another recursive version with setTimeout:
(function count(cc) {
document.getElementById("cco").innerHTML = cc;
if (cc > 0)
setTimeout(function() { count(--cc); }, 1000);
})(10);
When making countdown make sure that start and end elements are correct.
Count up:
for (var x=0;x < 10;x++) console.log(x);
goes from 0 to 9
Incorrect countdown:
for (var x=10;x > 0;x--) console.log(x);
goes from 10 to 1
Correct countdown:
for (var x=10-1;x >= 0;x--) console.log(x);
goes from 9 to 0