Skip to content

Commit 73dfc76

Browse files
committed
suggest to place examples in file
1 parent 5b93328 commit 73dfc76

File tree

1 file changed

+2
-0
lines changed

1 file changed

+2
-0
lines changed

_posts/2012-11-5-async.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ for (var i = 0; i < 100; i++) {
2020
console.log('You might think this gets printed last.')
2121
{% endhighlight %}
2222

23+
Copy the code above into a new file that you'll use for the rest of this lab. The points being illustrated require to be running the examples from a .js file.
24+
2325
Notice the value printed is 100, which is the terminal condition for this loop. This is because the callback for setTimeout doesn't actually get executed until the for loop has completed. Any other statements after the for loop would also be executed before the callback. This is, in part, because Node is single threaded. The event loop hasn't had a chance to invoke your callback. In any case, all of the callbacks are being fired with the same value of `i`.
2426

2527
How do we avoid this? The important concept here is how scope is handled in JavaScript. Unlike other languages that use block level scope, JavaScript's scope is at a function level. We can get around this problem by introducing a new scope in each iteration of the loop to capture the value of `i` at that moment:

0 commit comments

Comments
 (0)