好吧,我已经阅读了这里和网络上其他地方提出的关于类似问题的 20 个其他问题,但最终都是他们不喜欢,正确设置了一个变量并假设clearInterval 是基于函数 ID 或类似的东西。 这是我得到的(还有更多,但相当冗长,据我了解这是重要的一点):
var fan1 = function () {
var f1 = setInterval("flare1baserotate()",10);
setTimeout("clearInterval(f1)",2000);
};
基本上,“fan1()”函数被正确调用,setInterval 正确运行,因为“flare1baserotate()”函数正确运行并每 10 毫秒旋转我的对象,但问题出现在“clearInterval(f1)”处“20 秒后并没有像我认为的那样正常运行。 我需要做什么才能让它在 20 秒后清除?
最佳答案
如果您使用 setTimeout
的字符串或setInterval
,里面的代码会在全局 window
中运行范围,而不是调用它的范围。 f1
在函数 fan1
内声明因此无法从 clearInterval(f1)
行获得它在全局 window
中执行范围。一种简单的解决方案是制作 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);
};
关于javascript - clearInterval 不起作用,间隔未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25003028/