简单的同步输出
先看一个例子
for(var i=0;i<5;i++){
console.log(i)
}
这个代码很简单,会输出01234
加上setTimeout
那如果加上setTimeout
呢,例
for(var i=0;i<5;i++){
setTimeout(function(){
console.log(i)
},i)
}
执行结果就会变成这样
输出55555
,聪明如你 你会想到是因为异步回调的原因
这时候我想让这个回调函数里面的跟前面一样怎么办呢?
闭包保存变量
如果需要保持setTimeout
打印正确的值,那就需要闭包了
例:
for(var i=0;i<5;i++){
(function(i){
setTimeout(function(){
console.log(i)
},i)
})(i)
}
结果如图