Jump to content

[SOLVED] countdown


Sesquipedalian

Recommended Posts

Hey everyone,

 

I'm new to Javascript and I'm not sure why my countdown isn't working... Please give any advice you have!

 

<script>
function MyTimer () {
var first;
var min;
var sec;
if (first !== 1) {
	sec = 0;
	min = 3;
	first = 1;
}
if (min > 0) {
	if (min == 1) {
		document.getElementById('minutes').innerHTML = min+' minute and';
	} else {
		document.getElementById('minutes').innerHTML = min+' minutes and';
	}
}
if (sec == 1) {
	document.getElementById('seconds').innerHTML = sec+' second';
} else {
	document.getElementById('seconds').innerHTML = sec+' seconds';
}
if (sec === 0 && min > 0) {
	sec = 60;
	min--;
} else {
	sec--;
}
setTimeout(MyTimer(),1000);
}
</script>

You have <span id="minutes"></span> <span id="seconds"></span> left.
<script> MyTimer();</script>

 

Thanks,

 

-

Adam

Link to comment
https://forums.phpfreaks.com/topic/111284-solved-countdown/
Share on other sites

There are a few problems with that code.

 

1. The setTimeout function is called like this

setTimeout(MyTimer, 1000);

Note there are no brackets following the function name.

 

2. Your variables only have local scope. The min, sec & first variables are renewed each time the function runs. So, even if you fixed item #1 you would see 3 minutes constantly because each call to the function would have it thinking it was the first time run.

 

3. When reducing the seconds at the end of a minute you need to go to 59 seconds not 60. (Ex: if you have 2 minues and 0 seconds and take away one second you have 1 minute and 59 seconds, not 1 minute and 60 seconds)

 

Link to comment
https://forums.phpfreaks.com/topic/111284-solved-countdown/#findComment-573051
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.