Javascript in normal is Synchronous
Exectue line by line, but with code change you can act sometime as Asynchronous, but it's not actually going to execute on a separate thread.
Ok, what if you want to print Done
just after the Document.write is done
length = 0;
for(var i = 0; i < 5; i++)
{
setTimeout(function(index){
console.log('Iteration ' + index + ' <br>');
length++;
callback();
}(i),1000);
}
function callback(){
if(length == 5)
console.log('DONE!');
}
What we did here is we increment the counter and try to call the callback after each time its incremented and when counter reach 5 that mean all the 5 functions is called and then we are able to print Done
.
And as a side and important note, you was trying to print 0, 1, 2, 3, 4 but actually when you run your code it will give you 5, 5, 5, ,5, 5 because you write i
and i
at the point when you print is reached 5 and that's why it go out of the for loop, but you notice the code i added, i pass i
as an argument to the function so that it will save the value for us and when time to execute the funtion it will write 0, 1, 2, 3, 4