0

I have this little snippet (this is inside of an object):

var tout = 0;
self.initialize = function() {
    for (var key in periods) {
        setTimeout(function() {
            self.server.sendData('customData', periods[key], 0);
        }, tout);
        tout = tout + 7000;
    }
}

As you can see, I'm iterating through periods object fields, and I need each key to be visible inside my setTimeout() separately. Currently, that is not possible. I was trying something like this, hoping for a miracle:

self.initialize = function() {
    for (var key in periods) {
        var localkey = key; //here is the change
        setTimeout(function() {
            self.server.sendData('customData', periods[localkey], 0);
        }, tout);
        tout = tout + 7000;
    }
}

But obviously, a miracle did not happen. Does anyone have any idea on how to approach this issue?

ojek
  • 9,680
  • 21
  • 71
  • 110

1 Answers1

0
self.initialize = function() {
    for (var key in periods) {
        (function(key) {
            setTimeout(function() {
                self.server.sendData('customData', periods[key], 0);
            }, tout);
            tout = tout + 7000;
        })(key);
    }
}
James M
  • 18,506
  • 3
  • 48
  • 56
  • 1
    Just... Wow. That works. Thank you, this is something new to me. Could you explain a little bit? – ojek Nov 28 '14 at 23:27
  • It's using an [immediately invoked function expression](http://en.wikipedia.org/wiki/Immediately-invoked_function_expression) to create a new scope, passing your variable as a parameter. Inside the function, it's a separate variable so doesn't change as the loop progresses. – James M Nov 28 '14 at 23:49