简体   繁体   English

clearInterval不起作用,间隔未定义

[英]clearInterval not working, Interval Undefined

Okay, so I've read like 20 other questions asked here and elsewhere on the web concerning a similar thing, but it all ended up being that they didn't like, set a variable properly and assumed the clearInterval was based on a function ID or some such thing. 好的,所以我读了20处类似的问题,在这里和其他地方都问过,但这最终导致他们不喜欢,正确设置了变量,并假设clearInterval基于函数ID或类似的东西。 Here's what I've got (there's more, but it's rather lengthy and from I understand this is the important bit): 这是我所拥有的(还有更多,但很长,据我了解,这很重要):

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

Basically, the "fan1()" function gets called properly, the setInterval runs properly, as the "flare1baserotate()" function properly runs and rotates my object every 10 milliseconds, but the problem comes in where "clearInterval(f1)" doesn't run properly after 20 seconds as I feel it should. 基本上,“ fan1()”函数会正确调用,setInterval会正常运行,因为“ flare1baserotate()”函数会正确运行并每隔10毫秒旋转一次我的对象,但是问题出在“ clearInterval(f1)”不存在的地方我想应该20秒后才能正常运行。 What do I have to do to get it to clear after 20 seconds? 我要怎么做才能在20秒后清除它?

use this instead: 改用这个:

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

If you use a string with setTimeout or setInterval , the code in it will be run in global window scope, rather than the scope from where its called. 如果将字符串与setTimeoutsetInterval ,则其中的代码将在全局window范围(而不是调用它的范围)中运行。 The f1 declared inside the function fan1 is thus not available from the line clearInterval(f1) which gets executed in global window scope. f1函数内声明fan1因此不能从线clearInterval(f1)其被在全局执行window范围。 One easy solution would be to make f1 global. 一种简单的解决方案是使f1全局化。

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

And the recommended practice is to use closures rather than passing lines of code as strings. 推荐的做法是使用闭包而不是将代码行作为字符串传递。

And a hard way without globals might look like 没有全局变量的困难方法可能看起来像

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM