先来一个
for (var i=0; i < 5; i++) { setTimeout(function(){ console.log(i); }, 1000); } console.log(i);
答案:5,5,5,5,5,5
进化一下
期望是:5,0,1,2,3,4
这里就用到闭包
for (var i = 0; i < 5; i++) { setTimeout((function (i) { return function () { console.log(i); } })(i), 1000); } console.log(i);
还要进化
期望是:0,1,2,3,4,5
这就需要异步操作,Promise
var Pro = new Promise(function (resolve, reject) { for (var i = 0; i < 5; i++) { setTimeout((function (i) { return function () { console.log(new Date().getTime(), i); } })(i), 1000); } setTimeout(function () { resolve(i); }, 1000); }); Pro.then(function (res) { console.log(new Date().getTime(), res); })