常常有業務需求,要等幾秒才進行下一步操做。還能夠進行防抖節流。bash
// 利用回調函數
function sleep(callback,time) {
if(typeof callback === 'function') {
setTimeout(callback,time)
}
}
function output(){
console.log(1);
}
sleep(output,1000);
複製代碼
// Promise
const sleep = (time) => {
return new Promise((resolve, reject) => {
setTimeout(resolve, time);
})
}
sleep(5000).then(() => {
console.log('業務代碼')
})
複製代碼
const sleep = (time) => {
return new Promise((resolve, reject) => {
setTimeout(resolve, time);
})
}
async function sleepAsync () {
await sleep(5000);
console.log('業務代碼')
}
sleepAsync()
複製代碼
//Generator
const sleep = (time) => {
return new Promise((resolve, reject) => {
setTimeout(resolve, time);
})
}
function* sleepGenerator(time) {
yield sleep(time);
}
sleepGenerator(5000).next().value.then(()=>{
console.log('業務代碼')
})
複製代碼