共计 620 个字符,预计需要花费 2 分钟才能阅读完成。
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')
})();
正文完
发表至: javascript
2020-09-09