Joined June 2017
·

craigphicks

·

Posted to Be careful with setTimeout in loops over 1 year ago

<html>
<head></head>
<body>
Using setTimeout in the example loop will not behave as expected, if you expect that there will be a one second interval between each task. What happens instead is the whole loop is executed in under a millisecond, and each of the 5 tasks is scheduled to be placed on the synchronous JS event queue one second later. They will run consecutively in order, but not each separated by a second.

The desired behavior can be realized by using so-called "recursive" syntax, e.g., by calling the next setTimeout from inside the cllback function itself. Actually it is not true recursive because the calling function returns before the new scheduled task runs, so the stack does not increase in size. This is important because you would never run out of stack space using the so-called "recursive" syntax.

I have created a
<a href="https://jsfiddle.net/craigphicks/702p020d/">short program on jsfiddle</a>
to demonstrate the above behaviors.
</body>
</html>

Achievements
1 Karma
0 Total ProTip Views