CODER11713
CODER11713

Reputation: 79

setInterval not stopping?

I thought an interval just delayed the function, but as it turns out it actually loops.

When I include some function that stops the interval after the deletor function ends it doesn't trigger that and I still get Test logged to the console.

document.addEventListener("DOMContentLoaded", function(event) {
  let fullURL = window.location.href;
  //let fullURL2 = window.location.host + window.location.pathname;

  if (fullURL === "https://net.adjara.com/" ||
    fullURL === "https://net.adjara.com/Home") {
    var timer = setInterval(deletor, 5);

    function deletor() {
      timer;

      var slider = document.querySelector("#slider-con");
      var bannerTop = document.querySelector("#MainContent > div:nth-child(2)")
      var bannerMiddle = document.querySelector("#MainContent > iframe");
      var bannerRandom = document.querySelector("#MainContent > div:nth-child(3)");

      if (slider) {
        slider.parentNode.removeChild(slider);
      }

      if (bannerTop) {
        bannerTop.parentNode.removeChild(bannerTop);
      }

      if (bannerMiddle) {
        bannerMiddle.parentNode.removeChild(bannerMiddle);
      }

      if (bannerRandom) {
        bannerRandom.parentNode.removeChild(bannerRandom);
      }

      function stopInterval() {
        clearInterval(timer);
      }
      console.log("Test");

      /*if ()
      clearInterval(timer);*/
    };
  } else {
    return false;
  }
});

Upvotes: 2

Views: 78

Answers (2)

John
John

Reputation: 436

The code you provided works ¯\_(ツ)_/¯

Maybe the problem is coming from what triggers stopInterval()

But as mentioned in comments / other answers, you might be better off with another method

I wouldn't recommend using setTimeout in your case, because it looks like you are simply waiting for some DOM elements to be loaded. The problem with the timeout is that you can't know for sure how fast is the computer that will run your code. Maybe a bad quality phone with an outdated software that will need way more time to run your code than when you test on your personal computer, and that will not have the elements loaded by the time your function will be executed.

jQuery

For this reason, and since you tagged your question with jQuery I think you could use $(elementYouWaitForTheDOM2beLoaded).ready(function2execute) for each element you are watching instead of a having a loop that waits for the elements to be loaded (documentation for "ready" function)

Vanilla JS

And if you want to do it in pure JS it would be document.querySelector(elementYouWaitForTheDOM2beLoaded).on('load', function2execute))

Upvotes: 0

user1143094
user1143094

Reputation: 151

What you're looking for is setTimeout. It runs only once.

setTimeout(deletor, 5);

Also, you don't need to write timer variable inside of your closure like you would in Python. Javascript captures everything that's inside of lexical scope.

Upvotes: 1

Related Questions