0

Below is my javascript code:

function showBranch_init() {
    var id_arr = ["jdc_b1","jdc_b2","jdc_b3","jdc_b4"];
    for(a=0;a<id_arr.length;a++){
        timeoutID = window.setTimeout(function() {

            showBranch(id_arr[a]); // <-- Right here

        }, 500);
    }
}

How can I pass the value of id_arr[a] to showBranch funcion?

Currently the above code returns null for id_arr[a]

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Jo E.
  • 7,822
  • 14
  • 58
  • 94

3 Answers3

6

by introducing a new scope (by a function call) for each iteration step you can pass the argument like this:

function showBranch_init() {
    var id_arr = ["jdc_b1","jdc_b2","jdc_b3","jdc_b4"];
    for(a=0;a<id_arr.length;a++){
        (function(i) {
            timeoutID = window.setTimeout(function() {
                showBranch(id_arr[i]); // <-- Right here
            }, 500*i);
         })(a);
    }
}
  • Updated to fullfill the 2nd req: showBranch() in 500ms steps..
fast
  • 885
  • 7
  • 15
  • 2
    Please don't use the term "closure" to describe this kind of solution. The callback passed to `setTimeout` is *already* a closure. The actual solution is to create a new scope by executing a function, not by creating yet another closure. Whether the executed function is a closure or not doesn't have anything to do with it. – Felix Kling Feb 12 '14 at 09:38
  • 2
    +1 but define the function outside the for loop, because it creates one **each time** you iterate – axelduch Feb 12 '14 at 09:39
0

http://jsfiddle.net/HXc4d/

function showBranch_init() {
    var id_arr = ["jdc_b1","jdc_b2","jdc_b3","jdc_b4"];
    for(a=0;a<id_arr.length;a++){
        timeoutID = window.setTimeout(function(idvalue) {
            showBranch(idvalue);
        }(id_arr[a]), 500);
    }
}

EDIT: The problem with your solution is the fact that when the code executes (timeout) id_arr no longer exists in the executing scope, thus leading to undefined result. When sending the variable as an argument it "stays" with the funciton itself, regardless of the executing scope.

Sgoldy
  • 786
  • 3
  • 14
-1
function showBranch_init() {
var id_arr = ["jdc_b1","jdc_b2","jdc_b3","jdc_b4"];

    timeoutID = window.setTimeout(function() {
      for(a=0;a<id_arr.length;a++){
        showBranch(id_arr[a]); // <-- Right here
      }
    }, 500);
}

can you do that?? O_O

JohnnyJS
  • 1,320
  • 10
  • 21