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

  • 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.

主站蜘蛛池模板: 五常市| 敦煌市| 天长市| 沙河市| 南乐县| 贡觉县| 卢湾区| 黄平县| 晋江市| 藁城市| 大连市| 隆化县| 满洲里市| 安阳市| 平邑县| 彭州市| 札达县| 平武县| 什邡市| 广德县| 华安县| 嘉兴市| 桐庐县| 陕西省| 安国市| 吴桥县| 陇南市| 玉屏| 镇雄县| 宜章县| 汪清县| 鄯善县| 喀什市| 南岸区| 衢州市| 惠来县| 龙岩市| 库尔勒市| 安新县| 宁德市| 永仁县|