I have a simple Bootstrap page that includes a 45 second countdown timer and a button which I intend to include on a bigger project later. The countdown timer will start on a click of the button.
What I wanted to do is that when I click on the button again within the 45 seconds countdown interval, the counter will reset. I am not able to do that. What I tried to do is to use the clearInterval function at the very beginning of the errorTimer function. But, it did not work.
Here are my codes:
// Timer for error message - 45 seconds. function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function() { minutes = parseInt(timer / 60, 10) seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) { timer = duration; } }, 1000); } function errorTimer() { var fortyFiveSeconds = 60 * .75, display = document.querySelector('#time'); startTimer(fortyFiveSeconds, display); }; <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.min.js"></script> <div class="container-fluid"> <div class="row"> <div class="col-md-12 mt-5"> </div> </div> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4 text-center"> <p id="time"></p> </div> <div class="col-md-4"></div> </div> </div> <button type="button" class="btn btn-info" onclick="errorTimer()">Submit Button</button>
setInterval()returns anidfor the created and running interval. You need to store it on a variable if you want to clear ir later. Then you can callclearInterval(<some_id>);.