-2

I have this code snippet , basically I want to add some interval in between calling myfunc for each element in myCol .

         Promise.all(
                _.map(myCol, (o) ->
                  setTimeout =>
                    myfunc(o)
                    10000)
              )

With above implementation , myfunc is getting called without any interval

Dibshare
  • 95
  • 2
  • 13

1 Answers1

0

The problem is that the map function is setting the timeouts all at once. What you need to do is have the map function return after (n+1) lots of 10 seconds where n is the index of the element in myCol.

As I don't have _.map, I'll show you with array.prototype.forEach:

const myCol = [1,2,3,4];
const myFunc = console.log;

myCol.forEach((o,i) => setTimeout(myFunc, (i+1)*1000, o));

So, (i+1)*1000 set the timeouts to run i seconds after the call to forEach ends. For your code, change 1000 to 10000.

Of course if you don't want a delay for the first one, just do i*1000.

Also note that I'm putting o as the last parameter in setTimeout. The way you have it now, the function being called by setTimeout is the result of calling myfunc not myfunc itself.

Matt Ellen
  • 11,268
  • 4
  • 68
  • 90