Just as a learning exercise, I set out making a stopwatch without looking up how to do it etc.
I know it will have been done many times before. I'm just looking for some feedback on what I should do to make the code more efficient / cleaner / in keeping with standards etc.
// declare vars
var secondsDiv = $("#seconds");
var minsDiv = $("#mins");
var hoursDiv = $("#hours");
var interval = null;
var timer = false;
// return the value of a given div
function getCurrentValue(value) {
return value.html();
}
// reset the value of a chosen div to 00
function resetValue(value){
value.html("00");
}
// check if values are more than 59 to progress the timer
function check59() {
var currentSec = getCurrentValue(secondsDiv);
var currentMins = getCurrentValue(minsDiv);
var currentHours = getCurrentValue(hoursDiv);
// check the seconds to become a minute
if (currentSec > 59) {
currentMins++;
if (currentMins < 10) {
minsDiv.html("0" + currentMins);
} else {
minsDiv.html(currentMins);
}
resetValue(secondsDiv);
}
// check the minutes to become an hour
if (currentMins > 59) {
currentHours++;
if (currentHours < 10) {
hoursDiv.html("0" + currentHours);
} else {
hoursDiv.html(currentHours);
}
resetValue(minsDiv);
}
}
// add seconds
function addSecond() {
var currentSec = getCurrentValue(secondsDiv);
currentSec++;
if (currentSec < 10) {
secondsDiv.html("0" + currentSec);
} else {
secondsDiv.html(currentSec);
}
check59();
}
// run the initial addSecond function every second
$("#startTimer").click(function(){
if (timer===false) {
timer = true;
interval = setInterval(addSecond, 1000);
}
});
// stop the addSecond function every second
$("#pauseTimer").click(function(){
clearInterval(interval);
timer = false;
});
// reset all values
$("#clearTimer").click(function(){
resetValue(secondsDiv);
resetValue(minsDiv);
resetValue(hoursDiv);
});