LoginSignup
27
24

More than 5 years have passed since last update.

for文内でsetTimeoutを使う場合の変数のスコープ

Last updated at Posted at 2015-01-20

期待通りの結果にならない例

var array = [1, 2, 3],
    len   = array.length,
    i;

for(i = 0; i < len; i++){
    console.log(i); //0,1,2
    setTimeout(function() {
        console.log(array[i]); //undefined×3  >このコンソールは全てarray[3]にアクセスしている
    }, i * 1000);
};
console.log(i); //3  >条件式で3回インクリされた状態で残る

変数iをクロージャでキープすることで期待通りの結果に

var array = [1, 2, 3],
    len   = array.length,
    i;

for(i = 0; i < len; i++){
    console.log(i); //0,1,2
    (function(pram) {
        setTimeout(function() {
            console.log(array[pram]); //1,2,3
        }, pram * 1000);
    })(i);
};

bindを使っても同じ結果が

var array = [1, 2, 3],
    len   = array.length,
    i;
for(i = 0; i < len; i++) {
    setTimeout(function(index) {
        console.log(array[index]);
    }.bind(null, i), i * 1000);
}
console.log(i);

Underscore.jsのeachを使っても同じ結果が

var array = [1, 2, 3];

_.each(array, function(obj) {
  setTimeout(function() {
    console.log(obj);
  }, obj * 1000);
})
27
24
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
27
24