开发者

Shared data problem

I have a code like this:

var increment = 200;

for (var j=0; j<10; j++){

  var print = function(){ console.log("===== J ===== "+j); }

  setTimeout(print, increment); 

  increment+= 200;

}  

Console always print 10. I think that could be f开发者_如何转开发or statement and setTimeout are executed in different threads. How i can do to print the correct value of j?

Thanks in advance.


This is a standard binding issue, you can find a lot of similar questions on stackoverflow.

Basically, it is using one 'j' for all values. Try this instead:

function getBoundLog(j)
{
   return function(){console.log("===== J ===== "+j);}
}
var increment = 200;

for (var j=0; j<10; j++){

  setTimeout(getBoundLog(j), increment); 

  increment+= 200;

} 


You have scope problem I think. You are basically over writing the print function 10 times and because you wait to call the function with setTimeout by the time it gets called the function is actually

var print = function(){ console.log("===== J ===== "+10); }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜