What Jason said is perfectly correct in his answer, but I thought I would do it to better clarify.
This is actually a classic closure problem. This usually looks something like this:
for(var i = 0; i < 10; i++){ setTimeout(function(){ console.log(i); },i * 1000) }
The newbie should expect the console to show:
0 (0 seconds pass...) 1 (1 second passes...) 2 (etc..)
But this is not so! What you actually see is the number 10 , recorded 10 times (1 time per second)!
"Why is this happening?" Great question. Closing. In the for loop above, there is no scope, since in javascript only functions (lambdas) have a limited scope!
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Anyway! Your attempt would achieve the desired performance if you tried this:
json.objects.forEach(function(obj,index,collection) { setTimeout(function(){ console.log('foobar'); self.insertDesignJsonObject(obj, index); }, index * 5000); });
Since you have access to a "private" index variable, you can rely on the state that is expected when the function (lambda) is called!
Other sources:
How do JavaScript locks work?
http://javascript.info/tutorial/closures
http://code.tutsplus.com/tutorials/closures-front-to-back--net-24869
The dembinski
source share