我正在尝试制作一个 chrome 扩展,在我的 content script
中,它只在 www.youtube.com
上运行,它应该检查,文档。 getElementById("movie_player")
,是否加载了特定的 div
元素。如果不是 setInterval
并等待一秒钟。如果已加载,则运行 alert("Hello")
和 clearInterval
,这将结束脚本。
但是,它不起作用。即使在我找到该元素并显示“Hello”后,它仍会继续打招呼,这意味着 setInterval
仍在 1000 毫秒后调用我的函数,即使它应该已被清除。
这是我的 content.js
文件:
var timeOut;
function CheckDOMChange()
{
moviePlayer = document.getElementById("movie_player");
if(moviePlayer !== null)
{
WhenVideoLoads();
}
timeOut = setInterval("CheckDOMChange();", 1000);
}
function WhenVideoLoads()
{
alert("Hello");
clearInterval(timeOut);
}
CheckDOMChange();
如您所见,我将 timeOut
设为全局变量,因此它不应该是范围问题。所以我真的不知道问题出在哪里,因为正在满足条件并且正在调用 clearInterval
。
如有任何帮助,我们将不胜感激。
最佳答案
问题是函数中有 setInterval
。基本上,对于每次调用,您都在设置间隔,这会创建多个 setIntervals。从函数中删除 setInterval
var timeOut;
function CheckDOMChange() {
moviePlayer = document.getElementById("movie_player");
if (moviePlayer !== null) {
WhenVideoLoads();
}
}
function WhenVideoLoads() {
alert("Hello");
clearInterval(timeOut);
}
timeOut = setInterval("CheckDOMChange();", 1000);
关于javascript - clearInterval 在 javascript chrome 扩展中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47901458/