0

node.js newbie here. I'm looping through an array of objects, and setting a timeout for doing some ops using each object individually, the timeout for each objects also depends on some key-value within the object. The code is here:

for (var idx in arr) {
var obj = arr[idx];
interval = obj['key'];
setTimeout(function(){my_func(obj);}, interval);
}

Now what is failing here is that whenever a timeout occurs and the code block for my_func is called, it always acts on the last object in the array, probably because the variable 'obj' at that time points to it. How do I get around this? I am guessing I need a pass by reference, or something similar. Please point me in the right direction if I'm missing something here.

Chetan
  • 1,724
  • 2
  • 14
  • 18
  • Since you are using Node, use `let` instead of `var` and the problem will be solved. Btw, this has nothing to do with "pass by reference" (which JavaScript doesn't have anyway). – Felix Kling May 13 '16 at 13:51

1 Answers1

0

You will need to use closure for this:

for (var idx in arr) {
  var obj = arr[idx];

  (function( obj ){
    interval = obj['key'];
    setTimeout(function(){my_func(obj);}, interval);
  })( obj );
}//for()
Mohit Bhardwaj
  • 9,650
  • 3
  • 37
  • 64
  • 2
    Code is correct, but not the explanation. The way closures work is the *problem* here. The function passed to `setTimeout` is already a closure. What we need is a *new scope* per iteration and *calling* a function gives us that. Whether *that* function is a closure or not is mostly irrelevant. – Felix Kling May 13 '16 at 13:50
  • Thanks guys. I would agree with Felix. This link solved my problem, mostly along the lines of what you guys suggested here http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Chetan May 13 '16 at 13:51
  • okay. Thanks @FelixKling, I will try to look into it more. – Mohit Bhardwaj May 13 '16 at 14:00