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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.