/
setTimeout-patterns.js
87 lines (70 loc) · 1.77 KB
/
setTimeout-patterns.js
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* [x] 1. setTimeout in IIFE
* [x] 2. setTimeout in a func of an obj literal
* [x] 3. setTimeout in function expression
*/
// 1. IIFE - GOOD:
var reps = 3;
(function doStuff() {
if (reps == 0)
return;
console.log(reps);
reps--;
setTimeout(doStuff, 1000);
})();
// 2. obj lit - BAD:
var obj = {
rep: 5,
doStuff: function () {
if (this.rep == 0) {
return;
} else {
console.log(this.rep);
this.rep--;
setTimeout(this.doStuff, 1000);
}
}
};
// var inst = obj;
// inst.doStuff();
// 2. obj lit GOOD:
var obj2 = {
count: 3,
repeat: function () {
// bring vars down here so inner function can contain the variable count in it's closure scope
var enclosedCount = this.count;
function doSomething() {
if (enclosedCount == 0) {
return;
} else {
console.log(enclosedCount);
enclosedCount--;
setTimeout(doSomething, 1000);
}
}
doSomething();
}
};
// var inst = obj2;
// inst.repeat();
// 3. Function expression
var myFunc = function () {
var outer = 3;
function doStuff() {
var inner = 3;
if (outer == 0) {
return;
} else {
for (; inner> 0; inner--) {
console.log("in: " + inner);
}
console.log("outer: " + outer);
outer--;
setTimeout(doStuff, 1000);
}
}
doStuff();
return "done"; // occurs after first loop completes. Use Async?
};
var doIt = myFunc();
console.log(doIt);