I have code that I want to wait for the function to finish before it starts the next part of the loop.
I simplify the scenario a bit (I use I/O in my normal case, here I'm just using setTimeout to try to understand what's happening):
var total = 0;
var starttime = Date.now();
for (i = 5; i > 0 ; i--) {
setTimeout(console.log("This should take " + i + " seconds and be displayed after " + total
+" seconds. It took " + (Date.now() - starttime) + "ms"),i*1000);
total += i;
}
var endtime = Date.now();
console.log( endtime - starttime );
My output is:
This should take 5 seconds and be displayed after 0 seconds. It took 24ms
This should take 4 seconds and be displayed after 5 seconds. It took 27ms
This should take 3 seconds and be displayed after 9 seconds. It took 29ms
This should take 2 seconds and be displayed after 12 seconds. It took 30ms
This should take 1 seconds and be displayed after 14 seconds. It took 30ms
30
Could someone help me understand and change to get my code to run for 14 seconds?
EDIT: This question is not the same as the sleep question (Stackoverflow suggested I explain why my question is different), because the fact that I'm using setTimeout is arbitrary. What I'm after is I want to know that the previous iteration of the loop has completed before I continue on to the next iteration.