高级前端js【Q422】JS 如何实现一个同步的 sleep 函数

JS 如何实现一个同步的 sleep 函数

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 429

Author 回答者: shfshanyue

const sleep = (ms) =>
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);

Author 回答者: kissshot

SharedArrayBuffer被禁用了。。。

Author 回答者: shfshanyue

@kissshot 貌似是因为有安全问题…

Author 回答者: Hishengs

function sleep (t = 1000) {
    console.log('>>> sleep start');
    let startTime = +(new Date());
    let curTime = startTime;
    while (true) {
        curTime = +(new Date());
        if (curTime - startTime >= t) break;
    }
    console.log('>>> sleep finish');
}
 
// test
sleep(3000);
console.log('>>> hi');
 
// output
>>> sleep start
// 3s later
>>> sleep finish
>>> hi

Author 回答者: Vi-jay

function sleepSync(ttl) {
  const now = Date.now();
  ttl *= 1000;
  while (Date.now() - now < ttl) {}
}