Reputation: 69
I am a beginner programmer, just started JavaScript. I found a countdown timer that looks like this,
Code Snippet :
var count=60 ;
var Time_counter=setInterval(timer, 1000) ;
function timer() {
count=count-1;
if(count <=1){
clearInterval(Time_counter);
alert("Game Over") ;
return;
}
document.getElementById("timer").innerHTML=count;
}
Now whenever I run this program, this timer runs instantly without any conditions, it happens even if I put conditions. It will run by itself even if I keep it in an onclick attribute in the input tag like this :
<input id="Timer_button" type="button" value="Time starter" onclick="timer()">
But still the same problem.Even if I don't call the function, it just runs.
Can anybody find out the problem in the code, is there something wrong going on here? Answers would be really really appreciated. Please advice required .
Upvotes: 0
Views: 153
Reputation: 932
The problem is that the setInterval(timer,1000) starts the process of counting down. You have it declared globally so it is executed as soon as the script is loaded. You have to put it in a function and only call it if it has not already been called.
Upvotes: 1
Reputation: 23580
One possibility: You can create a function to start the timer:
var count = 60;
var Time_counter = null;
function startTimer() {
Time_counter = setInterval(timer, 1000);
}
And then call this function on click:
[…] onclick="startTimer();" […]
Upvotes: 3