Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
3e0720c
commit 5793521
Showing
3 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
/** | ||
* Pause the thread for the determined time | ||
* | ||
* @example | ||
* sleep(); | ||
* sleep(2000); | ||
* | ||
* @example | ||
* (async function () { | ||
* console.log("Beep"); | ||
* await sleep(5000); | ||
* console.log("Boop"); | ||
* })(); | ||
* | ||
* @param {number} time - time in ms to pause the thread | ||
* @returns {any} | ||
*/ | ||
export async function sleep(time = 1000) { | ||
if (typeof time !== "number" || time < 0 || isNaN(time)) { | ||
throw new Error("Time must be a non-negative number"); | ||
} | ||
return new Promise(resolve => setTimeout(resolve, time)); | ||
} | ||
|
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | ||
import { sleep } from "./src/main"; | ||
|
||
describe("sleep.js", () => { | ||
beforeEach(vi.useFakeTimers); | ||
afterEach(vi.clearAllTimers); | ||
|
||
it("should return a promise", () => { | ||
expect(sleep()).toBeInstanceOf(Promise); | ||
}); | ||
|
||
it("should pause the thread for the determined time", async () => { | ||
const promise = sleep(10000); | ||
expect(vi.getTimerCount()).toBe(1); | ||
vi.advanceTimersByTime(10000); | ||
expect(promise).resolves; | ||
expect(vi.getTimerCount()).toBe(0); | ||
}); | ||
|
||
it("throws an error for negative time", async () => { | ||
try { | ||
await sleep(-100); | ||
throw new Error("Promise should not resolve"); | ||
} catch (error) { | ||
expect(error.message).toBe("Time must be a non-negative number"); | ||
} | ||
}); | ||
|
||
it("throws an error for non-numeric time", async () => { | ||
try { | ||
await sleep("abc"); | ||
throw new Error("Promise should not resolve"); | ||
} catch (error) { | ||
expect(error.message).toBe("Time must be a non-negative number"); | ||
} | ||
}); | ||
}); |