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. 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. What do I have to do to get it to clear after 20 seconds?

有帮助吗?

解决方案

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. The f1 declared inside the function fan1 is thus not available from the line clearInterval(f1) which gets executed in global window scope. One easy solution would be to make f1 global.

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);
};

其他提示

use this instead:

var f1 = setInterval(function() {flare1baserotate();},10);
setTimeout(function() {clearInterval(f1); },2000);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top