0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ansynchronus Function with Iteration

Last updated at Posted at 2017-06-25
(function test() {
  for (var i = 0; i < 10; i++) {
    setTimeout(function() {
      console.log(i)
    , 100});
  }
})();

Expected return would be

0
1
2
3
4
5
6
7
8
9

Actual return is

10
10
10
10
10
10
10
10
10
10

That happened because of setTimeout function, which receives the value after updating variable "i" 10 times.

It is to nest setTimeout function with self-invoking function, so you can pass the "i" value of each cycle moment to it!!

(function test() {
  for (var i = 0; i < 10; i++) {
    (function(i) {
      setTimeout(function() {
        console.log(i);
      }, 1000);    
    })(i);
  }
})();

The result would be

 0
1
2
3
4
5
6
7
8
9

In ES6,
You can only change "var" to "let" in for loop parenthesis, because "let" is scoped to the nearest enclosing block.

(function test() {
  for (let i = 0; i < 10; i++) {
    setTimeout(function() {
      console.log(i)
    , 100});
  }
})();

Cool!!

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?