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
Create a function and add click lister to button to call that function. Do somthing like this.
FIDDLE
I just want to suggest you to put it in
click
handler of your selector instead of doing that onwindow load
:Demo @ Fiddle
Also i need to suggest you that to use
$(function(){});
dom ready function instead ofwindow.onload = function(){};
just because dom ready does not wait for dom to get fully loaded to execute the script.You are expecting the function get work when you click and in your code you are using
onload
event.So use click() event of jQuery for your requirement.
You are attaching your function in
onLoad
of the page, instead attachonClick
Please check the fiddle JsFiddle
Use click event of action link with id= "startClock"
Use on method
$(selector).on('click',callback);