I have a function that I want to 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 initial 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?
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: