This is a common conceptual mistake.
- Javascript is non-blocking
- A reference to the variable is passed, not the actual value
You have to keep in mind, that the variable x is dynamic. A reference to x is passed to the alert("For loop iteration #" + x); not the value. Thus when the alert finally is executed x will have the value which it has at the point of execution not at the point where the setTimeout was initiated!
Essentially it goes like this:
Your loop is processed, creating 6 timeouts and immediately after that will show your alert("Code to be executed after completed for loop");. Then after the some time, your timeouts get executed which then will all show the variable x in it's state after the loop is finished - 6.
You need a closure so that the value of x gets handed over to the alert, not the reference to the variable x itself.
for (var x = 0; x <= 5; x++) {
(function(z) {
setTimeout(function() {
alert("For loop iteration #" + z);
}, 5 * z);
})(x);
}
EDIT:
To tackle your second problem, you need to use a callback function. A CB function is the logical continuation of your code, but shall not be executed immediately but needs to be stalled until a certain point (your last alert has occured). You would implement it like this:
for (var x = 0; x <= 5; x++) {
(function(z) {
setTimeout(function() {
alert("For loop iteration #" + z);
if (z===5){ continue_code() }
}, 5 * z);
})(x);
}
function continue_code(){
alert("Code to be executed after completed for loop");
// Here comes all your code
// which has to wait for the timeouts from your for loop
}
In the last setTimeout you call the function which continues the execution of your code.