Search code examples
javascripthtmltimer

How to toggle or pause setInterval in javascript


I am learning java Script and i am trying to create clock which should be "when I click the button, the time Should stop changing and the button Should change from “Stop time” to “Start time” & when I click the button again, the time should begin changing and the button should change from “Start time” to “Stop time”. See my codes and tell me which codes or function i need to add and where to add... I am newbie in it so i will appreciate your help..

<!DOCTYPE html>
<html>
<body>

<p>A script on this page starts this clock:</p>
<p id="demo"></p>

<button onclick="myStopFunction()">Stop time</button>
</body>
</html>

//---Script Here---

<script>
var myVar = setInterval(function(){ myTimer() }, 1000);

function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}

function myStopFunction() {
clearInterval(myVar);
}
</script>

Solution

  • Try this one

    let currentTime = new Date();
    let status = true;
    let interval = 1; // in seconds
    let dateFormat = { hour: 'numeric', minute:'numeric', second: 'numeric', hour12: true };
    
    let clock = document.querySelector('#demo');
        clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);
    
    let timer = setInterval(
        function () {
            currentTime.setSeconds(currentTime.getSeconds() + interval);
            clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);
        }, interval * 1000
    );
    
    let button = document.querySelector('#button');
        button.addEventListener('click', onClick);
    
    function onClick() {
        if (!status) {
            button.innerHTML = 'Stop timer';
    
            timer = setInterval(
                function () {
                    currentTime.setSeconds(currentTime.getSeconds() + interval);
                    clock.innerHTML = currentTime.toLocaleString('en-US', dateFormat);
                }, interval * 1000
            );
    
            return;
        }
    
        if (status) {
            button.innerHTML = 'Start timer';
            clearInterval(timer);
        }
    
        status = !status;
    }
    <p>A script on this page starts this clock:</p>
    <p id="demo"></p>
    
    <button id="button">Stop time</button>