How To Start Count-down Timer When "Start" Button Is Pressed

Hi folks,

How do I get my count-down timer to launch when I press my “Start-Resume” button?

Here is my current Javascript code:

`
//…under experimentation/construction…

$(document).ready(function(){ 

function startCountDown(){

var seconds = 60;
 function secondsPassed(){
 	//inside this function, new variable called minutes

	 	var minutes = Math.round((seconds-30)/60);
	 	//now going to add another variable inside function for remaining seconds
	 	var remainingSeconds = seconds % 60;

	 	 if (remainingSeconds < 10){
	 	 	remainingSeconds = "0" + remainingSeconds;
		}

		//Output the result in an element with id="number"
		document.getElementById('number').innerHTML = minutes + ":" + remainingSeconds

		//once remaining seconds reach none, interval is over so write some text
		 if( seconds == 0){
		 	clearInterval("number");
		 	document.getElementById("number").innerHTML= 'Buzz!!'; //temporary placeholder....will link to a buzz sound later
		 }else{
		 	seconds--; //decrements
		 }
	 }
	 var  number = setInterval('secondsPassed()', 1000);

	 $(".start-resume").click(function(){
    startCountDown();
 });
}



$('.start-resume').click(function(){ 
            $('#number').addClass("on"); 
}); 

});

`
Here is a link to my jsfiddle: https://jsfiddle.net/MenelikMakonnen/230xtgmb/5/

Thanks in advance for your help! Cheers!

Your problem is how you’re passing your function to setInterval. Check out the doucmentation - it gives examples on how to use it.

@PortableStick, I do not see how I am using the setInterval method wrong. Can you elaborate?

I think it’s better if you check the documentation for yourself. Carefully compare what you’ve written to the examples.

1 Like

Before I address the issue with setInterval, you first need to call the startCountDown function from outside the startCountDown function when the div with class=“start-resume” is clicked. Currently, your JSFiddle shows this click handler to be inside startCountDown.

As far as setInterval goes, it expects a function for the first parameter. You put a string ‘secondsPassed()’. Just put the function name but do not call it with () at the end. Also, your clearInterval should be a variable name and not a string which you are currently using.

@RandellDawson, thanks for these tidbits, I already got the problem solved. See here: https://jsfiddle.net/MenelikMakonnen/230xtgmb/