乐趣区

关于javascript: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')
})();
退出移动版