Last active
June 23, 2023 23:58
-
-
Save o-az/edcfb7473e86e88c8cda03f2d9fe9b60 to your computer and use it in GitHub Desktop.
Actual JavaScript 'sleep' function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param ms milliseconds to sleep | |
* @returns void | |
*/ | |
export function sleep(ms: number): void { | |
/** | |
* In some environments such as Cloudflare Workers, Atomics is not defined | |
* setTimeout is used as a fallback | |
*/ | |
if (typeof Atomics === 'undefined') { | |
new Promise((resolve) => setTimeout(resolve, ms)) | |
} else { | |
const AB = new Int32Array(new SharedArrayBuffer(4)) | |
Atomics.wait(AB, 0, 0, Math.max(1, ms | 0)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment