今天看到一道有趣的面試題,和大家伙分享一下
question: 實(shí)現(xiàn)一個sleep(3000)函數(shù),使js程序暫停3000毫秒.
總所周知js是單線程,所以當(dāng)js程序暫停三秒只需要占用js程序三秒造成好像是"sleep"了的感覺.
下面我們來實(shí)現(xiàn)吧
方法一: 樸實(shí)無華的循環(huán)
var sleep = (ms) => {
let startTime = newData().getTime();
for(;;){
let now = newData().getTime();
if(now - startTime >= ms) {
break;
}
}
sleep(3000)
方法二:定時器
function sleep1(ms, callback) {
setTimeout(callback, ms)
}
//sleep 1s
sleep1(1000, () => {
console.log(1000)
})
方法三:es6異步處理
const sleep = time => {
return new Promise(resolve => setTimeout(resolve,time)
) }
sleep(1000).then(()=>{ console.log(1) })
#### 方法四:yield后面是一個生成器 generator
function sleepGenerator(time) {
yield new Promise(function(resolve,reject){
setTimeout(resolve,time);
})
}
sleepGenerator(1000).next().value.then(()=>{console.log(1)})
方法五:es7---- async/await是基于Promise的言沐,是進(jìn)一步的一種優(yōu)化
function sleep(time) {
return new Promise(resolve =>
setTimeout(resolve,time)
) } async function output() {
let out = await sleep(1000);
console.log(1);
return out;
}
output();