Halo, i have function timer, but the timer is already run before i click start. how to solve it, i want when i click start, the timer will be running. if i deleted seconds++ in first function, the time not running even i click start button the time is still 0. Thank you for help. this is my code
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
h1.textContent = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
timer();
/* Start button */
start.onclick = timer;
/* Stop button */
stop.onclick = function() {
clearTimeout(t);
}
<h1><time>00:00:00</time></h1>
<button id="start">start</button>
<button id="stop">stop</button>
Remove timer(); from your code
function timer() {
t = setTimeout(add, 1000);
}
//timer();
/* Start button */
start.onclick = timer;