0

I am working on the snippet below. Is there a way to check whether the setInterval() is really killed or still running in background processing?

Technically what I need to do is killing the JS setInterval whenever the .map is not in the page. My understanding is the setInterval() still running every 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 Interval
    }
  }, 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>
halfer
  • 19,824
  • 17
  • 99
  • 186
Behseini
  • 6,066
  • 23
  • 78
  • 125

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
  • 91,784
  • 22
  • 134
  • 156
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
  • 57
  • 6