Skip to content

Instantly share code, notes, and snippets.

@o-az
Last active June 23, 2023 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save o-az/edcfb7473e86e88c8cda03f2d9fe9b60 to your computer and use it in GitHub Desktop.
Save o-az/edcfb7473e86e88c8cda03f2d9fe9b60 to your computer and use it in GitHub Desktop.
Actual JavaScript 'sleep' function
/**
* @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