github linkedin rss
JavaScript: Async in loops
Mar 22, 2014

For quite a while I have planned to write posts, and I even have a document where I store ideas. But due to limited time, and the nagging feeling that I must create a masterpiece, nothing really happens.

Well now I have this radical idea – it might be better to write smaller posts more frequently, instead of once every 6 months / never. This won’t be as demanding, and it will hopefully make me a bit more active. If it might give someone something of value then why not?

This post will be an hands-on example of async JavaScript, as I suspect that this is something that some might struggle with it.

Example

Say that you have a list of items that you wish to perform some async operation on (like writing to a file). Your code might look something like this:

If you run the code you will note that “Hello Michael” gets printed five times. This is caused by the fact that the for-loop already has finished after the 10 ms that setTimeout is set to.

What you probably want is this:

When the code in setTimeout refers to a variable in the outer function something called a “closure” is created. This will make sure that “name” is kept in memory until setTimeout has finished.


Back to posts