发布于 3年前

js sleep函数

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')
})();
©2020 edoou.com   京ICP备16001874号-3