replaced for loops with recursive functions

this ensures that everything happens in the correct order instead of
just assuming that the setTimeouts will be precise enough.