javascript - 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;
}
});
解决方案
您正在寻找的是setTimeout。它只运行一次。
setTimeout(deletor, 5);
此外,您不需要像在 Python 中那样在闭包内编写计时器变量。Javascript 捕获词法范围内的所有内容。
推荐阅读
- dialogflow-es - 有没有办法通过 Dialogflow 向电报机器人发送位置?
- c - 使用此数组代码无法获得很大的总和
- visual-c++ - 为什么 xmm11 在优化代码中不保留交叉调用?
- ios - Swift:使用present时无法在视图控制器之间传递数据
- python - 如何使用 Jenkins 中分离的变量、关键字和测试文件构建 Robot Framework 项目
- r - 使用 rollapply 计算每周百分比变化
- identityserver4 - 解密 Identity Server 中的共享密钥
- javascript - 为什么控制台显示 js 代码,即使我没有在单独的文件中?
- java - 使用 Spring Boot 和 Thymeleaf 上传多个文件
- css - React native:试图在滚动时隐藏搜索栏