- JavaScript:Moving to ES2015
- Ved Antani Simon Timms Narayan Prusty
- 231字
- 2021-07-09 19:07:33
Loops and closures
Consider the following example of using functions inside loops:
for (var i=1; i<=5; i++) { setTimeout( function delay(){ console.log( i ); }, i*100); }
This snippet should print 1
, 2
, 3
, 4
, and 5
on the console at an interval of 100 ms, right? Instead, it prints 6
, 6
, 6
, 6
, and 6
at an interval of 100 ms. Why is this happening? Here, we encounter a common issue with closures and looping. The i
variable is being updated after the function is bound. This means that every bound function handler will always print the last value stored in i
. In fact, the timeout function callbacks are running after the completion of the loop. This is such a common problem that JSLint will warn you if you try to use functions this way inside a loop.
How can we fix this behavior? We can introduce a function scope and local copy of the i
variable in that scope. The following snippet shows you how we can do this:
for (var i=1; i<=5; i++) { (function(j){ setTimeout( function delay(){ console.log( j ); }, j*100); })( i ); }
We pass the i
variable and copy it to the j
variable local to the IIFE. The introduction of an IIFE inside each iteration creates a new scope for each iteration and hence updates the local copy with the correct value.
- Data Visualization with D3 4.x Cookbook(Second Edition)
- Backbone.js Blueprints
- 從Java到Web程序設(shè)計教程
- Java程序設(shè)計入門
- Flowable流程引擎實戰(zhàn)
- 人工智能算法(卷1):基礎(chǔ)算法
- Python從入門到精通(第3版)
- C語言程序設(shè)計
- 深度實踐KVM:核心技術(shù)、管理運維、性能優(yōu)化與項目實施
- 邊玩邊學(xué)Scratch3.0少兒趣味編程
- 從零開始學(xué)Unity游戲開發(fā):場景+角色+腳本+交互+體驗+效果+發(fā)布
- Learning NHibernate 4
- Mastering R for Quantitative Finance
- Python AI游戲編程入門:基于Pygame和PyTorch
- Hands-On GUI Application Development in Go