极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。

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

Issue

欢迎在 Gtihub Issue 中回答此问题: Issue 429 (opens new window)

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

Author

回答者: kissshot (opens new window)

SharedArrayBuffer (opens new window)被禁用了。。。

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

Author

回答者: Hishengs (opens new window)

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 (opens new window)

function sleepSync(ttl) {
  const now = Date.now();
  ttl *= 1000;
  while (Date.now() - now < ttl) {}
}
Last Updated: 6/26/2022, 10:48:10 AM