clearInterval无法在javascript chrome扩展中使用

问题描述 投票:1回答:2

我正在尝试制作镀铬扩展,并在我的content script只运行在www.youtube.com它应该检查,document.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被调用。

任何帮助将非常感激。

javascript html google-chrome google-chrome-extension
2个回答
1
投票

问题是你在函数内部有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);

1
投票

通过递归调用CheckDOMChange,您实际上是以指数方式创建计时器,而您只是在调用WhenVideoLoads时清除最后一个计时器。

您可以尝试运行此代码段并检查控制台以查看发生的情况,并看到单击该按钮将清除最后一个计时器,但不会清除之前创建的所有计时器。

var timeOut;
var counter = 0;

function CheckDOMChange()
{   
	console.log("counter :", counter);
  if (counter > 16) {
    console.log("Stop creating new timers!");
    return;
   }

  timeOut = setInterval("CheckDOMChange();", 5000);
	console.log("timeOut :", timeOut);
	counter ++;
}
function WhenVideoLoads()
{
  console.log("Clearing ", timeOut);
  clearInterval(timeOut);
}
CheckDOMChange();
<button onclick="WhenVideoLoads()" id="clear">Clear timer</button>

你应该避免递归调用CheckDOMChange,然后继续@cdoshi建议。

希望这可以帮助!

© www.soinside.com 2019 - 2024. All rights reserved.