I am creating a simple JavaScript Timer. Firstly, here's my code that I'm working with:
//Variables used for the timer
var timer = "waiting",
seconds = 0,
minutes = 0,
extraFill1 = "",
extraFill2 = "";
//Check whether to start or stop the timer
function toggleClock() {
if (timer === "waiting") {
setInterval(start, 1000);
timer = "executing";
document.getElementById("btn").innerText = "Stop";
}
else {
clearInterval(start);
timer = "waiting";
document.getElementById("btn").innerText = "Start";
}
}
//Increment seconds and display correctly
function start() {
seconds++;
//Add a leading zero for 1 digit numbers (seconds)
if (seconds < 10 || seconds === 60) {
extraFill1 = "0";
}
else {
extraFill1 = "";
}
//Increment minute when seconds reaches 60
if (seconds === 60) {
minutes += 1;
seconds = 0;
}
//Add a leading zero for 1 digit numbers (minutes)
if (minutes < 10) {
extraFill2 = "0";
}
else {
extraFill2 = "";
}
//display results
document.getElementById("result").innerHTML = extraFill2 + minutes + ":" + extraFill1 + seconds;
}
In my first function toggleClock()
, I have stated that if timer !== waiting
, then we do clearInterval(start). I would like to clearInterval(start)
if timer === "executing
. This does not work (which I think is because it has a local scope?). To solve this, I attempted writing:
var myTimer = setInterval(start, 1000);
I planned on calling myTimer when I wanted to start the timer. Instead, the interval kicks off as soon as the page is loaded (and the variable is declared).
How might I set an interval of a function (on button click) with the ability to stop/clear the interval (by pressing the same button) later?