I am showing a timer on a bootstrap modal popup. I am using setInterval to start a timer. It is working fine for the first time but after the closure of popup and when I open the popup again, timer doesn't show up.
https://jsfiddle.net/8h49o7Lg/
code
var timer = setInterval(clock, 1000);
var sec = 00;
var min = 00;
function clock() {
sec += 1;
if (sec == 60) {
min += 1;
sec = 00;
}
document.getElementById("timerid").innerHTML = min + ":" + sec;
}
Oh that's really simple, you just create a new timer every time you open the popup, but you don't get rid of the old one.
I think the simplest solution would be to just clear it the moment you try to assign it again.
var timer;
function showtimer(){
if (timer) clearInterval(timer);
timer = setInterval(clock, 1000);
var sec = 00;
var min = 00;
function clock() {
sec += 1;
if (sec == 60) {
min += 1;
sec = 00;
}
document.getElementById("timerid").innerHTML = min + ":" + sec;
}
}
As I mentioned in my comment, you do not clear the timer since it was local to the showTimer
Here is a better solution where I also reset the timer display and pad the numbers
let timer;
function showtimer() {
timer = setInterval(clock, 1000);
var sec = 00;
var min = 00;
function clock() {
sec += 1;
if (sec == 60) {
min += 1;
sec = 00;
}
document.getElementById("timerid").innerHTML = String(min).padStart(2, "0") + ":" + String(sec).padStart(2, "0");
}
$('#myModal').modal('show');
}
$(document).on('hidden.bs.modal', '#myModal', function(event) {
clearInterval(timer);
document.getElementById("timerid").innerHTML = "00:00";
});
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<button type="button" class="btn btn-info btn-lg" onclick="showtimer()">Open Modal</button>
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<div id="timerid">00:00</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>