views:

46

answers:

1

Hi,

I have a function that I wanna execute several times for different dom elements, for example element A,B,C, and D. This function is recursive, meaning that when it finishes its execution it runs again, after some timeout, for the same element.

Now, I want that element A starts the execution before B,C and D. Also B starts before D and B and so on. I tried the following

setTimeout(execute(A),1000);
setTimeout(execute(B),2000);
setTimeout(execute(C),3000);
setTimeout(execute(D),4000);

function execute(element){
    doSomething();
    setTimeout(execute(element),5000);
}

I don't know if this is correct way of doing it. The problem is that if I set the innitial timeout values all the same, so that they all start at the same time, everything works fine. But if not, like the example above, then sometimes it works, sometimes not, I mean it always works, the problem is that they don't seem to follow the same sequence of time. I see that they start in different points of time but after some seconds, for example there are some already at the same time...

Any idea? Thanks

+1  A: 

It would probably be better to implement some kind of queue that keeps track of the elements to apply the function to, and let it keep track of which element to execute for next.

Pseudocode:

Call function with an array of elements to execute for and optionally an interval

Function:
    Get the next element from the queue.
    Execute a helper function with the retrieved element
    Put the element back last in the queue
    Set a timeout for the next execution time
PatrikAkerstrand