javascript - How to pass parameter to an anonymous function defined in the setTimeout call? - Stack Overflow

Here is my code:function addRcd2(timeOut){for(var c=0; c less 5; c++){var rcdi = "rcd_"+c+&

Here is my code:

function addRcd2(timeOut){  
  for(var c=0; c less 5; c++){
    var rcdi = "rcd_"+c+"";
    setTimeout(function(){
      $('.tbl1 tbody').append(rcdi);
    },timeOut*c);
  }
}

The output of this code is a table which rows have the same text rcd_5.

My goal is to have a table rows have different records rcd_1, …, rcd_5.

Any ideas?

Here is my code:

function addRcd2(timeOut){  
  for(var c=0; c less 5; c++){
    var rcdi = "rcd_"+c+"";
    setTimeout(function(){
      $('.tbl1 tbody').append(rcdi);
    },timeOut*c);
  }
}

The output of this code is a table which rows have the same text rcd_5.

My goal is to have a table rows have different records rcd_1, …, rcd_5.

Any ideas?

Share Improve this question edited Jun 18, 2011 at 12:50 insumity 5,4718 gold badges38 silver badges65 bronze badges asked Jun 18, 2011 at 12:49 antonjsantonjs 14.3k15 gold badges70 silver badges91 bronze badges 2
  • 1 That code should work. I don't see anything wrong with it. – Kon Commented Jun 18, 2011 at 12:51
  • 2 No it wont, it's a mon closure mistake – Halcyon Commented Jun 18, 2011 at 12:54
Add a ment  | 

2 Answers 2

Reset to default 7

Typical creating a function in a loop problem. All closures you pass to setTimeout have a reference to the same rcdi variable. Defining the variable inside the loop is the same as defining it outside:

var rcdi;
for(var c=0; c < 5; c++){
    rcdi = "rcd_"+c+"";
    // ...
}

which makes it a bit more apparent that you only deal with one variable here.

You have to introduce a new scope, which in JavaScript can only be achieved through functions:

function getCallback(val) {
    return function(){
      $('.tbl1 tbody').append(val);
    };
}

function addRcd2(timeOut){  
  for(var c=0; c < 5; c++){
    setTimeout(getCallback("rcd_"+c),timeOut*c);
  }
}

As you can see in other answers, you can also use immediate functions. Use what you find more readable.

function addRcd2(timeOut){  
  for(var c=0; c less 5; c++){
    var rcdi = "rcd_"+c+"";
    setTimeout((function(x) {
      return function(){
        $('.tbl1 tbody').append(x);
      };
    })(rcdi),timeOut*c);
  }
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745361672a4624389.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信