+ 3

Global and local variables and setinterval and clearinterval for JavaScript timer?

I am trying to build a simple JavaScript timer together with a pause-start button toggle. As a newcomer to JavaScript I cannot understand why the script below is not working. Instead of simple play/pause it seems to start several instances of timer concurrently? Any suggestions? ===== JavaScript file: // Define the button and timer variables globally let playPauseToggleButton = document.querySelector('#playPauseToggleButton'); let timerDuration = 5 * 60; // 5 minutes for the timer let timerPaused = true; playPauseToggleButton.addEventListener("click", pausePlay); // Define the start of the timer, which is triggered by the button pressing "Pause" or "Play" function startTimer(timerDuration, timerPaused) { function ticker () { timerDuration = timerDuration - 1; console.log(timerDuration); let display = document.querySelector('#mainbox'); display.innerHTML = timerDuration; } let timer = setInterval(ticker, 1000); if (timerPaused) { clearInterval(timerDuration); console.log('Cleared interval at', timerDuration); return timerDuration; } else { timer = setInterval(ticker(), 1000); return timerDuration; } } // Changing the button between "pause" and "play" function pausePlay(){ if (timerPaused == false) { console.log('You pressed to start', timerDuration); timerPaused = false; timerDuration = startTimer(timerDuration, timerPaused); playPauseToggleButton.innerHTML = "Pause"; } else { timerPaused = true; console.log('You pressed to pause', timerDuration); playPauseToggleButton.innerHTML = "Start"; timerDuration = startTimer(timerDuration, timerPaused); } } ===== html file includes: <button id="playPauseToggleButton">Play</button>

16th Mar 2020, 9:14 AM
Marko Rillo
7 odpowiedzi
+ 4
I just skip decrementing the <timerDuration> and updating the <display> text when <timerPaused> equals true. https://code.sololearn.com/WN1VMg8pumkR/?ref=app
17th Mar 2020, 2:51 AM
Ipang
+ 3
Thanks for thinking along Ipang - your solution is simple and straightforward indeed.
17th Mar 2020, 7:31 AM
Marko Rillo
+ 3
No problem Marko 👌
17th Mar 2020, 7:33 AM
Ipang
+ 2
Hello Biraj, thanks a lot for spending your time and attempting to suggest your solution and thinking about this. :-) Looking at your solution I still see the same bug that has been bothering me for some reason. When I press "pause" in your solution the timer does not stop, the timer countdown goes on? Do you also get the same error or is it just me for some reason?
16th Mar 2020, 9:05 PM
Marko Rillo
+ 2
Thanks Biraj, seems to work now indeed! Well done! :)
17th Mar 2020, 7:30 AM
Marko Rillo