0

Can you please take a look at this snippet and let me know if there is a way to check weather the setInterval() is really killed or still running in background processing?

Technically what I need to do is killing the JS setinerval whenever the .map is not in the page. my understanding is the setInterval() still running ever 2 second just is not writing on the console because of if statement

setInterval(
  function() {
    if ($(".map")[0]) {
      console.log("Map is in the Page");
    } else {
     //Stop Inreval
    }
  }, 2000);
  
  setTimeout(function(){ $(".box").empty(); 
  }, 9000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
  <div class="map">Map in Here</div>
</div>
Behseini
  • 5,746
  • 20
  • 67
  • 114

2 Answers2

1

You need to call clearInterval() to stop the execution of the intervalled function.

Here's an example:

let i = 3;

let interval = setInterval(function() {
  if (i > 0) {
    console.log("Running " + i--);
  } else {
    clearInterval(interval);

    console.log("Stopped");
  }
}, 2000);
Robby Cornelissen
  • 81,630
  • 19
  • 117
  • 142
1

In order to kill an interval or timeout you should assign it to a variable for referencing. The specific functions are: clearInterval(your interval reference variable name) and clearTimeout(your timeout reference variable name).

var yourInterval = setInterval(
  function() {

    console.log("Still running?"); //for testing purpose.

    if ($(".map")[0]) {
      console.log("Map is in the Page");
    } else {
      clearInterval(yourInterval); //it kills this interval, if the interval already terminated, it won't do anything harm, nor produce an error message in the browser console.
    }
  }, 2000);
  
  setTimeout(function(){ $(".box").empty(); 
  }, 9000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
  <div class="map">Map in Here</div>
</div>
L. Cang
  • 47
  • 6