0

I have a function that reloads the page every 2 seconds and it starts with the first load. I want this reload to stop as soon as I click the Modal Bootstrap 4.7 button. My code works ok if I click within the first 2 seconds interval. Otherwise it no longer obeys my call. why?

var myTimer = null;

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

function stopTimer() {
  clearInterval(myTimer);
  myTimer =null;
}

document.addEventListener("DOMContentLoaded", function() {
  startTimer();
});

$('#idModalButton').click(function(){
      stopTimer();
      $('#idModal').modal('show');
    });

I also tried the following without success..same problem..only works in the first 2 seconds.

const myInterval = setInterval(myTimer, 2000);
    function myTimer() {
      somefunction();
    }
    

    $(document).on("click", "#idButtonModal", function(){ 
      clearInterval(myInterval);
      $('#idModal').modal('show');
    });
stats con chris
  • 178
  • 1
  • 10
  • I'm guessing that _"reload the page"_ means parts of the document are replaced dynamically. If that includes your button, any attached event handlers will be lost. Use event delegation instead – Phil Mar 21 '22 at 00:45
  • thanks..exactly that's my case. I hope you can elaborate more so I can easily grasp event delegation – stats con chris Mar 21 '22 at 00:59

0 Answers0