I have built a timer program in JavaScript. It decrements one counter every second, and if that counter is at zero, it decrements another counter, and sets the first counter to 59. If the second counter now is below zero, then it stops the timer. Would it be more efficient to store the total seconds left, and calculate the minutes on the fly? Is there other stuff I can improve on?
var timerRun; // Variable for holding the interval
var timeLeft; //Array; index 0 keeps track of the minutes, and index 1 keeps track of the seconds
var timerRunning = false; //Boolean to keep track of whether the timer is running
function tick() {
// Subtract 1 second
timeLeft[1] -= 1;
if (timeLeft[1] < 0) { // Decrement the minute if neccessary
timeLeft[0] -= 1;
timeLeft[1] = 59;
}
if (timeLeft[0] < 0) { // Check if the timer is done
clearInterval(timerRun);
alert("Timer is done!");
timerRunning = false;
document.getElementById("timer").innerHTML = "Simple Timer";
}
if (timeLeft[1] < 10) { // Display the seconds as a two-digit number
timeLeft[1] = "0" + timeLeft[1];
}
document.getElementById("timer").innerHTML = timeLeft.join(":");
if (timerRunning == false) {
document.getElementById("timer").innerHTML = "Simple Timer";
}
}
function time() { // Restart timer
clearInterval(timerRun)
timerRun = setInterval(tick, 1000);
// Create array
timeLeft = document.getElementById("time").value.split(":");
timerRunning = true;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 id="timer">Simple Timer</h1>
<input type="text" id="time" value="15:00">
<button type="button" onclick="time();" id="start">Start</button>
</body>
</html>