在JS,要实现sleep,可以异步函数实现,代码:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
console.log('Taking a break...');
await sleep(2000);
console.log('Two seconds later');
}
demo();
执行demo方法后 ,使用await 关键字等待sleep方法执行完,而demo定时在两秒后执行,以此实现sleep。
参考:
https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep
https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/0014345008539155e93fc16046d4bb7854943814c4f9dc2000
https://segmentfault.com/a/1190000007535316