js实现sleep效果教程
程序员文章站
2022-12-09 15:48:59
1.使用promise
function sleep(ms){
var temple=new promise(
(resolve)=>{...
1.使用promise
function sleep(ms){ var temple=new promise( (resolve)=>{ console.log(111);settimeout(resolve,ms) }); return temple } sleep(500).then(function(){ console.log(222) })
2.使用async
function sleep(ms){ return new promise((resolve)=>settimeout(resolve,ms)); } async function test(){ var temple=await sleep(1000); console.log(1111) return temple } test();
3.使用generator
function* sleep(ms){ yield new promise(function(resolve,reject){ console.log(111); settimeout(resolve,ms); }) } sleep(500).next().value.then(function(){console.log(2222)})