+ 2

Stop clock function not working

I wanna create a clock that prints the current time when I click a "Start Clock" Button, and Stops it when I click "Stop clock", But my function is not working, why ? // ************** HTML ****************** // <h1 id="timer"> 00:00:00 </h1> <button id="start-clock" onclick="startTime()"> Start Clock </button> <button id="stop-time" onclick="stopTime()"> Stop Clock</button> // ************** JS code **************** // var si; var start = document.getElementById('start-clock'); var clock = document.getElementById('timer'); function startTime() { let dateObj = new Date().toLocaleTimeString(); // let hours = dateObj.getHours(); // let minutes = dateObj.getMinutes(); // let sec = dateObj.getSeconds(); // let time = ` Clock Started \n ${hours} : ${minutes} : ${sec}`; clock.innerHTML = dateObj; si = setInterval(startTime, 1000); } function stopTime() { clearInterval(si); }

25th Nov 2021, 8:06 PM
Marina Khamis
Marina Khamis  - avatar
5 Respostas
+ 3
// ************** HTML ****************** // <h1 id="timer"> 00:00:00 </h1> <button id="start-clock" onclick="startTime()"> Start Clock </button> <button id="stop-time" onclick="stopTime()"> Stop Clock</button> // ************** JS code **************** // var si = null; var clock = document.getElementById('timer'); function myTimer() { let dateObj = new Date(); clock.innerHTML = dateObj.toLocaleTimeString(); } startTime = () => { if (si == null) si = setInterval(myTimer, 1000); } stopTime = () => { if (si != null) { clearInterval(si); si = null; } } https://code.sololearn.com/WO5qt5KLK273
25th Nov 2021, 9:33 PM
SoloProg
SoloProg - avatar
+ 1
function myTimer() { let dateObj = new Date(); clock.innerHTML = dateObj.toLocaleTimeString(); } function startTime() { si = setInterval(myTimer, 1000); }
25th Nov 2021, 9:19 PM
SoloProg
SoloProg - avatar
25th Nov 2021, 11:27 PM
Jairo Soto
Jairo Soto - avatar
+ 1
@SoloProg Thank you sooo much, it worked !
26th Nov 2021, 1:28 PM
Marina Khamis
Marina Khamis  - avatar
- 1
Loco escríbeme por WhatsApp
26th Nov 2021, 2:49 AM
AZP AGROSERVICIOS