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>