(function(){ /*for(var i = 0; i < 5; i++){ setTimeout(function(){ console.log(new Date(), i) },1000) } console.log(new Date(), i); //55555 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 (function(){ /*for(var i = 0; i < 5; i++){ (function(i){ setTimeout(function(){ console.log(',' + i); }, 1000); })(i); } console.log(i);*/ /*var name = 'aaa'; for(var i = 0; i < 5; i++){ setTimeout(function(i,name){ console.log(i + name); },1000,i,name); } console.log(i);*/ /*var output = function(i){ setTimeout(function(){ console.log(i); }, 1000); } for(var i = 0; i < 5; i++){ output(i); } console.log(i);*/ /*for(let i = 0; i < 5; i++){ setTimeout(function(){ console.log(i); }, 1000); } console.log(i); //报错了*/ /*let name = 'aadfdfa'; function alertName(){ alert(name); } alertName();*/ /*for(var i = 0; i < 5; i++){ } var i = 0; var inter = setInterval(function(){ if(i <= 5){ console.log(i) i++ }else{ clearInterval(inter); } },1000); */ /*for(var i = 0; i < 5; i++){ (function(j){ setTimeout(function(){ console.log(j); }, 1000*j); })(i); } setTimeout(function(){ console.log(i); }, 1000*i)*/ //promise版本 /*const tasks = []; for(var i = 0; i < 5; i++){ ((j)=>{ function resolve(){ console.log('aaaaaaaaa'); } tasks.push(new Promise((resolve)=>{ setTimeout(()=>{ console.log(j); resolve(); },1000*j); })); })(i); } Promise.all(tasks).then(()=>{ setTimeout(function(){console.log(i);}, 1000) });*/ //promise简洁版 /*const tasks = []; const output = (i)=> new Promise((resolve)=>{ setTimeout(()=>{ console.log(i); resolve(); }, 1000*i); }); for(var i = 0; i < 5; i++){ tasks.push(output(i)); } Promise.all(tasks).then(()=>{ setTimeout(()=>{ console.log(i); }, 1000) })*/ const sleep = (timeStamp) => new Promise((resolve)=>{ setTimeout(resolve, timeStamp); }) (async ()=>{ //报错了,可能是我的babel还不支持,谢谢 for(var i = 0; i < 5; i++){ if(i > 0){ await sleep(1000); } console.log(i); } await sleep(1000); console.log(i); })() })();