You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: Closures/README.md
+68-1Lines changed: 68 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -203,4 +203,71 @@ Closures are a powerful feature in JavaScript, enabling data privacy, function f
203
203
204
204
---
205
205
206
-
**Practice:** Try modifying the examples in `closures.js` and observe the results to deepen your understanding.
206
+
## setTimeout, Closures, and Loop Pitfalls
207
+
208
+
This section explains how closures interact with `setTimeout` and loops, a common source of confusion in JavaScript.
209
+
210
+
### Example 1: The Problem with `var` in Loops
211
+
```js
212
+
functiony() {
213
+
for (var i =1; i <=5; i++) {
214
+
setTimeout(() => {
215
+
console.log(i);
216
+
}, i *1000);
217
+
}
218
+
}
219
+
y();
220
+
```
221
+
**What happens?**
222
+
- This will log `6` five times (after 1s, 2s, ..., 5s).
223
+
- Why? Because `var` is function-scoped, not block-scoped. By the time the callbacks run, the loop is done and `i` is `6`.
224
+
225
+
### Example 2: Fix with IIFE (Immediately Invoked Function Expression)
226
+
```js
227
+
functionz() {
228
+
for (var i =1; i <=5; i++) {
229
+
(function(closeI) {
230
+
setTimeout(() => {
231
+
console.log(closeI);
232
+
}, closeI *1000);
233
+
})(i);
234
+
}
235
+
}
236
+
z();
237
+
```
238
+
**How does this work?**
239
+
- The IIFE creates a new scope for each iteration, capturing the current value of `i` as `closeI`.
240
+
- Each timeout callback now has its own copy of the value.
241
+
- This logs `1, 2, 3, 4, 5` as expected.
242
+
243
+
### Example 3: Fix with `let`
244
+
```js
245
+
functiona() {
246
+
for (let i =0; i <5; i++) {
247
+
setTimeout(() => {
248
+
console.log(i);
249
+
}, i *1000);
250
+
}
251
+
}
252
+
a();
253
+
```
254
+
**How does this work?**
255
+
-`let` is block-scoped, so each iteration gets a new binding of `i`.
256
+
- Each callback closes over its own `i` value.
257
+
- This logs `0, 1, 2, 3, 4` as expected.
258
+
259
+
### Key Concepts
260
+
-**Closures** allow the callback to "remember" the variable from its surrounding scope.
261
+
- With `var`, all callbacks share the same variable, leading to unexpected results in async code.
262
+
- Use `let` or an IIFE to capture the correct value for each iteration.
263
+
264
+
**Summary:**
265
+
> When using asynchronous functions like `setTimeout` inside loops, always be mindful of variable scope. Use `let` or an IIFE to avoid common pitfalls with closures and `var`.
266
+
267
+
268
+
---
269
+
270
+
**Practice:** Try modifying the examples in `closures.js` & `setTimeOutPractice.js` and observe the results to deepen your understanding.
0 commit comments