clearInterval不工作,Interval未定义

clearInterval not working, Interval Undefined

本文关键字:Interval 未定义 工作 clearInterval      更新时间:2023-09-26

好吧,所以我在这里和网上其他地方读到了20个关于类似事情的其他问题,但最终都是他们不喜欢,正确设置了一个变量,并假设clearInterval是基于函数ID或类似的东西。以下是我得到的(还有更多,但相当长,据我所知,这是重要的一点(:

var fan1 = function () {
    var f1 = setInterval("flare1baserotate()",10);
    setTimeout("clearInterval(f1)",2000);
};

基本上,"fan1(("函数被正确地调用,setInterval正确地运行,就像"flare1baserotate(("功能正确地运行并每10毫秒旋转一次我的对象一样,但问题在于"clearInterval(f1("在20秒后没有像我认为的那样正确地运行。我该怎么做才能在20秒后将其清除?

如果将字符串与setTimeoutsetInterval一起使用,则其中的代码将在全局window范围内运行,而不是在调用它的范围内运行。在函数fan1内部声明的f1因此从在全局window作用域中执行的行clearInterval(f1)不可用。一个简单的解决方案是使f1全局化。

var f1;
var flare1baserotate = function(){console.log("hi");};
var fan1 = function () {
    f1 = setInterval("flare1baserotate()",10);
    setTimeout("clearInterval(f1)",2000);
};

推荐的做法是使用闭包,而不是将代码行作为字符串传递。

没有全球化的艰难道路可能看起来像

var flare1baserotate = function() {
    console.log("hi");
};
var fan1 = function() {
    var f1 = setInterval("flare1baserotate()", 10);
    setTimeout((function(f1) {
        return function() {
            clearInterval(f1);
        }
    })(f1), 2000);
};

使用以下内容:

var f1 = setInterval(function() {flare1baserotate();},10);
setTimeout(function() {clearInterval(f1); },2000);