[英]Once Again: SetInterval Doesn't Stop
I know this question has been asked many times, but I'm unable to figure out my problem with those solutions.我知道这个问题已经被问过很多次,但我无法用这些解决方案找出我的问题。 My setInterval doesn't stop.
我的 setInterval 不会停止。 I've set up a mutation observer to check if a error pops-up.
我已经设置了一个突变观察器来检查是否弹出错误。 If it does, I want to present a custom message.
如果是这样,我想展示一条自定义消息。
let elem = document.querySelector("#Page > div");
let observer = new MutationObserver(mutationRecords => {
// console.log(mutationRecords); // console.log(the changes)
let my_interval = setInterval((interval) => {
err_msg = document.querySelector("#ErrorMessage");
if(err_msg != null){
if(err_msg.innerText == "Custom Message"){clearInterval(my_interval);}
console.log(err_msg.innerText);
err_msg.innerText = "Custom Message";
clearInterval(my_interval);
}
}, 10);
});
observer.observe(elem, {
childList: true, // observe direct children
subtree: true, // and lower descendants too
characterDataOldValue: true // pass old data to callback
});
Please help me out.请帮帮我。
Thanks.谢谢。
Why do you need a MutationObserver AND a setInterval?为什么需要 MutationObserver 和 setInterval? They seem like two different approaches to the problem to me (watching for changes).
对我来说,它们似乎是解决问题的两种不同方法(观察变化)。 If you start a setInterval in the mutation observer handler, a new interval will be created on each DOM update -- so there might be more than one setInterval running at a time.
如果您在变异观察器处理程序中启动一个 setInterval,则每次 DOM 更新时都会创建一个新的时间间隔——因此可能同时运行多个 setInterval。
Looking at the logic in the mutation observer, the interval is only stopped if #ErrorMessage exists when the interval fires.查看变异观察器中的逻辑,只有在间隔触发时存在#ErrorMessage 时才会停止间隔。
So you will have a setInterval for each mutation, but only clear them on certain conditions, possibly leaving some running.因此,您将为每个突变设置一个 setInterval,但仅在特定条件下清除它们,可能会留下一些运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.