Make countdown start after button is clicked
30,208
Solution 1
Use click event of action link with id= "startClock"
$("#startClock").click( function(){
var counter = 5;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
if (counter === 0) {
alert('sorry, out of time');
clearInterval(counter);
}
}, 1000);
});
Solution 2
Create a function and add click lister to button to call that function. Do somthing like this.
function startTimer(){
var counter = 5;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
if (counter === 0) {
alert('sorry, out of time');
clearInterval(counter);
}
}, 1000);
}
function start()
{
document.getElementById("count").style="color:green;";
startTimer();
};
button
{
font-size:40px;
background-color:black;
color:white;
}
#count
{
margin-left:20px;
font-size:30px;
color:black;
}
<span id="count">5</span> seconds
<br>
<button onclick="start()">
START
</button>
Author by
Lauren
Updated on September 11, 2020Comments
-
Lauren over 3 years
I'm creating a kid's game with a timer countdown that starts after the user clicks a button.
The code I'm using initiates the countdown without a problem, but I'd like the countdown to start only after the button is clicked.
Here is my code:
window.onload = function(){ (function(){ var counter = 5; setInterval(function() { counter--; if (counter >= 0) { span = document.getElementById("count"); span.innerHTML = counter; } if (counter === 0) { alert('sorry, out of time'); clearInterval(counter); } }, 1000); })(); }
Thank you! Lauren
-
Admin over 10 years
-
Admin over 10 years
-
-
Lauren over 10 yearsWorks great. Thank you everyone for your help!