将函数传递给循环中的setTimeout:总是最后一个值? [英] Passing functions to setTimeout in a loop: always the last value?

查看:142
本文介绍了将函数传递给循环中的setTimeout:总是最后一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用setTimeout来执行我传递信息的匿名函数,但我遇到了麻烦。这个(硬编码版本)可以正常工作:

I'm trying to use setTimeout to execute an anonymous function that I pass information into and I'm having trouble. This (hard-coded version) would work just fine:

setTimeout(function(){alert("hello");},1000);
setTimeout(function(){alert("world");},2000);

但是我试图从数组中取出hello和world并将它们传递给函数而不用(a)使用全局变量,(2)使用eval。我知道如何使用全局或eval来做到这一点,但是如何在没有它的情况下做到这一点。这是我想做的(但我知道它不会起作用):

But I'm trying to take the hello and world from an array and pass them into the function without (a) using global variables, and (2) using eval. I know how I could do it using globals or eval, but how can I do it without. Here is what I'd like to do (but I know it won't work):

var strings = [ "hello", "world" ];
var delay = 1000;
for(var i=0;i<strings.length;i++) {
    setTimeout( function(){alert(strings[i]);}, delay);
    delay += 1000;
}

当然,字符串[i]将脱离上下文。如何在没有eval或globals的情况下将字符串[i]传递给该匿名函数?

Of course strings[i] will be out of context. How can I pass strings[i] into that anonymous function without eval or globals?

推荐答案

这是经常重复的如何在闭包问题中使用循环变量。

This is the very frequently repeated "how do I use a loop variable in a closure" problem.

规范的解决方案是调用一个函数,该函数返回一个绑定到循环变量当前值的函数:

The canonical solution is to call a function which returns a function that's bound to the current value of the loop variable:

var strings = [ "hello", "world" ];
var delay = 1000;
for(var i=0;i<strings.length;i++) {
    setTimeout(
        (function(s) {
            return function() {
                alert(s);
            }
        })(strings[i]), delay);
    delay += 1000;
}

外部定义 function(s){.. 。} 创建一个新范围,其中 s 绑定到所提供参数的当前值 - 即 strings [i] - 内部范围可用的地方。

The outer definition function(s) { ... } creates a new scope where s is bound to the current value of the supplied parameter - i.e. strings[i] - where it's available to the inner scope.

这篇关于将函数传递给循环中的setTimeout:总是最后一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆