sleep函数,顾名思义,等待一段时间后再执行

1,异步sleep,等待期间其他代码继续执行

function sleep(time, callback) {
 setTimeout(callback, time)
}
console.warn('sleep start')
//sleep 1s
sleep(1000, () => {
 console.log('sleep callback')
})
console.warn('code end')

promise写法

function sleep (time) { 
    return new Promise((resolve) => setTimeout(resolve, time)); 
}
// 用法 
console.warn('sleep start')
sleep(3000).then(() => { 
   console.log('sleep callback')
})
console.warn('code end')

2,同步sleep,等待期间中断代码执行

function sleep (time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}
(async function() {
 console.warn('sleep start');
 await sleep(3000);
 console.log('sleep callback')
 console.warn('code end')
})();

Jaywin
265 声望16 粉丝

一些花开在高高的树上,一些果结在深深的地下。ณۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗณۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗۗ...