originally I have something like this (ads is an array) :
for (var i = 0; i < ads.length; i++) {
asynchMeth(ad[i]);
}
asyncMeth is an asynchronous method that calls the server (I cannot make it synchronous). But I would like that asynchMeth(ad[i]) will start 3second after asynchMeth(ad[i-1]) has finished. The following doesn't work but it gives an idea on what I am looking for :
isWorking = false; //Will be set to true whenever asyncMeth starts, to false when it ends.
var i = 0;
var timer = setInterval(3000, function() {
if(!isWorking){
if(i < ads.length){
asyncMeth(ads[i]);
i++;
}
else{
clearInterval(timer);
}
}
});
How to work with setInterval when we are calling function with different/dynamic parameters ?
I would first add a callback to
asyncMeththat is called whenever the function has finished doing whatever it is doing. Otherwise there is no way to know ifasyncMethhas finished its work. In your example what you have isn't the same as what you want! You wantads[i]to process 3 seconds afterads[i - 1]has finished. Instead, what you have is code to start processingads[i]3 seconds afterads[i - 1]has started processing. With a callback toasyncMeth, you can then do this:Here you have a self-invoked function that initially accepts a parameter value of
0. This value is assigned to the parameteri. Ifiis lesser thanads.length, it means that we still have items to process. So it callsasyncMethwithads[i]as a parameter.But then we also provide a callback. In this callback we tell the callback to call
workwith the incremented the value ofi. This means thatworkwill start processing the next item.So now you can asynchronously-process each item one after the other until
ibecomes equal toads.length, at which point you have processed all the items.EDIT
I noticed that you mentioned that you want a 3-second delay. For that you can do this:
The only difference here is that the next iteration happens 3 seconds after the last one has completed.