Stop clock function not working | Sololearn: Learn to code for FREE!

+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); }

11/25/2021 8:06:35 PM

Marina Khamis

7 Answers

New Answer

+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

+1

function myTimer() { let dateObj = new Date(); clock.innerHTML = dateObj.toLocaleTimeString(); } function startTime() { si = setInterval(myTimer, 1000); }

+1

https://code.sololearn.com/WCy042Wl5Mxs/?ref=app

+1

@SoloProg Thank you sooo much, it worked !

-1

-1

Loco escríbeme por WhatsApp

-1

829-844-0223