首页 > 解决方案 > setInterval 没有停止?

问题描述

我认为间隔只是延迟了函数,但事实证明它实际上是循环的。

当我包含一些在deletor函数结束后停止间隔的函数时,它不会触发它,我仍然会Test登录到控制台。

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;
  }
});

标签: javascriptjqueryhtml

解决方案


您正在寻找的是setTimeout。它只运行一次。

setTimeout(deletor, 5);

此外,您不需要像在 Python 中那样在闭包内编写计时器变量。Javascript 捕获词法范围内的所有内容。


推荐阅读