# 实现一个 sleep 函数,比如 sleep(1000) 意味着等待1000毫秒
# 方式一
const sleep = (time) => {
return new Promise(resolve => setTimeout(resolve, time))
}
sleep(1000).then(() => {
// 这里写你的骚操作
console.log(1)
})
# 方式二
const sleep = (time) => {
return new Promise(resolve => setTimeout(resolve, time))
}
async function sleepAsync() {
console.log('fuck the code')
await sleep(1000)
console.log('fuck the code again')
}
sleepAsync()
# 方式三
//Generator
function* sleepGenerator(time) {
yield new Promise(function(resolve, reject){
setTimeout(resolve,time)
})
}
sleepGenerator(1000).next().value.then(()=>{
console.log(1)
})
# 方式四
function sleep(callback, time) {
if(typeof callback === 'function') {
setTimeout(callback, time)
}
}
function output(){
console.log(1)
}
sleep(output, 1000)