简体   繁体   English

在setTimeout函数方法中使用具有更改值的变量?

[英]Using a variable with changing value in setTimeout function approach?

Please let me know if I'm coming at this block on a wrong angle. 如果我以错误的角度来到这个街区,请告诉我。 I have a series of functions I'd like to fire off, and I'd like to be able to set them all up in a loop. 我有一系列功能,我想要启动,我希望能够将它们全部设置为循环。

for(var jj = 0; jj<monster.frames.length;jj++){
    setTimeout(
        functionName(jj),
        1000*jj
    );
}

The problem is that when that when functionName(jj) is exectuted, it's being passed the value of jj which by that time has been changed to the last loop iteration value. 问题是,当functionName(jj)被执行时,它将被传递jj的值,到那时它已被更改为最后一个循环迭代值。

You need to ensure the inner function has a new variable for every iteration. 您需要确保内部函数为每次迭代都有一个新变量。 The easiest way to do this is to create a self-executing anonymous function which receives the variable as an argument. 最简单的方法是创建一个自动执行的匿名函数,该函数接收变量作为参数。 You also need to fix the way you are calling the function - right now you register the return value of functionName(jj) as a callback. 您还需要修改调用函数的方式 - 现在您将functionName(jj)的返回值注册为回调functionName(jj) This would only be ok if that function actually returned a function. 只有当该函数实际返回一个函数时才会这样。

for(var jj = 0; jj<monster.frames.length;jj++){
    (function(jj) {
        setTimeout(
            function() { functionName(jj); },
            1000*jj
        );
    })(jj);
}

You can also use partial application to create a new function. 您还可以使用部分应用程序来创建新功能。 However, old browsers do not support Function.prototype.bind so you'd have to add a shim for it. 但是,旧浏览器不支持Function.prototype.bind因此您必须为其添加垫片。

for(var jj = 0; jj<monster.frames.length; jj++){
    setTimeout(functionName.bind(this, jj), 1000*jj);
}

Give this a go: 放手一搏:

for(var jj = 0; jj < monster.frames.length; jj++)
{
    (function(x)
    {
        setTimeout(function()
        {
            functionName(x)
        }, 1000 * x);
    })(jj);
}

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

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