How to pass parameter to an anonymous function defined in the setTimeout call?

后端 未结 2 1875
夕颜
夕颜 2021-01-22 21:38

Here is my code:

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


        
相关标签:
2条回答
  • 2021-01-22 22:08
    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);
      }
    }
    
    0 讨论(0)
  • 2021-01-22 22:35

    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.

    0 讨论(0)
提交回复
热议问题