Javascript runs tasks on a stack. Your for loop executes completely as one of those loops. When you use a setTimeout
it takes the function you passed in and appends it to the end of that task stack. Then it will execute that task when appropriate.
// current thread | waiting
doSomething(); // execute now | --
setTimeout(doSomething, 10); // append to stack | doSomething (8ms left)
doSomethingElse(); // execute now | doSomething (5ms left)
// End of current thread // -- | doSomething (0ms left) do this next
// doSomething | --
SetTimeout returns immediately as if it was finished. It basically assigns the function to a pending state and will be executed after the current thread is finished (current function is over/returned) and the timeout timer is finished.