Goose Goose - 7 months ago 87
Javascript Question

setTimeout not working inside forEach

I have a forEach that calls a function. There needs to be a delay between each time it is called. I've put it inside a setTimeout inside the forEach. It isn't respecting the timeout after the first wait. Instead it is waiting once, then running all at once. I've set the timeout to 5 seconds and I am using a console to confirm. 5 seconds of wait, then several foobar console logs all at once.

Why am I getting this behavior?

json.objects.forEach(function(obj) {
self.insertDesignJsonObject(obj, index);
}, 5000);


What Jason said is totally correct in his answer but I thought I would give it a shot, to better clarify.

This is a actually a classic closure problem. Typically it would look something like:

for(var i = 0; i < 10; i++){
    },i * 1000)

The novice would expect the console to show:

(1 second passes...)
(1 seconds passes..)

But that just isn't the case! What you would actually see is the number 10 getting log 10 times all-at-once!

"Why does that happen?" Great question. Closure scope. The for loop above lacks closure scope because in javascript, only functions (lambdas) have closure scope!


However! Your attempt would have achieved the desired output if you had tried this:

    json.objects.forEach(function(obj,index,collection) {
            self.insertDesignJsonObject(obj, index);
        }, index * 5000);

Because you have access to the "closur-ed" index variable - you can rely on its state being the expected state when the function (lambda) is invoked!

Other Resources:

How do JavaScript closures work?