0

I use Bootstrap 4.7 Modal on a page. This page also has a javascript function that reloads the page every second, e.g.,

setInterval(function () {
            somefunction();
        }, 1000);

The problem is that the Modal doesn't work. I guess it doesn't because the moment it pops up the page has to reload so it fails. Then I believe I need to tell setInterval to stop reloading if Modal is active? Is there an easy way around this? Thanks a lot

stats con chris
  • 178
  • 1
  • 10

1 Answers1

0

If you save the interval as a variable, you can stop it later hen a button is clicked (for example).

var myTimer = setInterval(function () {
  somefunction();
}, 1000);

Now just call clearInterval(myTimer) to stop it.


Or, let's really simplify it like this.

var myTimer = null;

function startTimer() {
  myTimer = setInterval(function () {
    somefunction();
  }, 1000);
}

function stopTimer() {
  clearInterval(myTimer);
}

Now you just need to call startTimer() and stopTimer()

Chris Barr
  • 29,851
  • 23
  • 95
  • 135
  • This seems ok without Bootstrap Modal. The problem with Modal is that $('#id').on('shown.bs.modal', function () { ... } seems not to act faster than the 1 second setInterval update, so when I click, sometimes it stops, sometimes it doesn't. I dont' know how to fix this – stats con chris Mar 20 '22 at 23:43