官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 平江县| 上栗县| 响水县| 台北市| 衡南县| 新余市| 会理县| 托克逊县| 申扎县| 寿阳县| 阿巴嘎旗| 文成县| 海林市| 甘泉县| 綦江县| 新丰县| 措美县| 林西县| 嘉义市| 黄浦区| 皋兰县| 诏安县| 连南| 安乡县| 石家庄市| 赤水市| 郑州市| 石泉县| 芜湖县| 清新县| 喀什市| 正阳县| 文山县| 阿拉善左旗| 奈曼旗| 高州市| 青龙| 克东县| 元氏县| 伊春市| 玉龙|