Pause display of a function

Asked

Viewed 31 times

-1

I made a program to be kind of a stopwatch after pressing the play button, but I can’t think of a logic of when I press the pause button the counter pause the display of the numbers where it is (without zeroing the numbers already shown) and then, if the play button was pressed again the count would continue from where it paused.

Code so far:

<body>
    <div id="number"></div>
    <button class="play" onclick="play()">Play</button>
    <button onclick="pause()">Pause</button>
    <script>
        var seg = 0;
        var min = 0;
        var l = document.getElementById("number");
        function play() {
            window.setInterval(function() {
                if (seg < 10) {
                    l.innerHTML = '0' + min + ':' + '0' + seg;
                    seg++;
                } else {
                    l.innerHTML = '0' + min + ':' + seg;
                    seg++;
                }
                if (seg > 60) {
                    seg = 0;
                    min++;
                    if (seg < 10) {
                    l.innerHTML = '0' + min + ':' + '0' + seg;
                    seg++;
                } else {
                    l.innerHTML = '0' + min + ':' + seg;
                    seg++;
                }
                }
            }, 1000);
        }
        function pause() {
            
        }
    </script>
</body>

1 answer

0

Friend Voce can look at the clearInterval as Rafel Tavares said

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval#examples

Or something as simple as a variable:

    <body>
    <div id="number"></div>
    <button class="play" onclick="play()">Play</button>
    <button onclick="pause()">Pause</button>
    <script>
        var seg = 0;
        var min = 0;
        var l = document.getElementById("number");
        var isPause = false;
        function play() {
            window.setInterval(function() {
                if(!isPause){
                if (seg < 10) {
                    l.innerHTML = '0' + min + ':' + '0' + seg;
                    seg++;
                } else {
                    l.innerHTML = '0' + min + ':' + seg;
                    seg++;
                }
                if (seg > 60) {
                    seg = 0;
                    min++;
                    if (seg < 10) {
                    l.innerHTML = '0' + min + ':' + '0' + seg;
                    seg++;
                } else {
                    l.innerHTML = '0' + min + ':' + seg;
                    seg++;
                }
                }
                }
            }, 1000);
        }
        function pause() {
            isPause = true;
        }
    </script>
</body>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.