forked from chuanxshi/javascript-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiife-for-loop.html
More file actions
40 lines (36 loc) · 1.18 KB
/
iife-for-loop.html
File metadata and controls
40 lines (36 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!doctype html>
<html lang="en">
<head>
<title>JavaScript Patterns</title>
<meta charset="utf-8">
</head>
<body>
<script>
/* Title: iife for loops
* Description: loops that make use of counters as expected
*/
// this will log 'regular loop 5'
for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log('regular loop', i);
}, 3000);
}
// this will log 'iife loop 1', 'iife loop 2', 'iife loop 3', 'iife loop 4'
for (var i = 0; i < 5; i++) {
(function(n) {
setTimeout(function() {
console.log('iife loop', n);
}, 3000);
})(i);
}
// same results as the iife loop. Let isn't supported by all javascript versions
for (let i = 0; i < 5; i++) {
setTimeout(function() {
console.log('let loop', i);
}, 3000);
}
// References
// http://benalman.com/news/2010/11/immediately-invoked-function-expression/
</script>
</body>
</html>