Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sleep(0) must yield event loop #3987

Merged
merged 1 commit into from
May 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/utils/src/sleep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {ErrorAborted} from "./errors";
* On abort throws ErrorAborted
*/
export async function sleep(ms: number, signal?: AbortSignal): Promise<void> {
if (ms <= 0) {
if (ms < 0) {
return;
}

Expand Down
37 changes: 36 additions & 1 deletion packages/utils/test/unit/sleep.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,41 @@ describe("sleep", function () {
controller.abort();
expect(controller.signal.aborted, "Signal should already be aborted").to.be.true;

await expect(sleep(10, controller.signal)).to.rejectedWith(ErrorAborted);
await expect(sleep(0, controller.signal)).to.rejectedWith(ErrorAborted);
});

it("sleep 0 must tick the event loop", async () => {
enum Step {
beforeSleep = "beforeSleep",
afterSleep = "afterSleep",
setTimeout0 = "setTimeout0",
}

const steps: Step[] = [];

setTimeout(() => {
steps.push(Step.setTimeout0);
}, 0);

steps.push(Step.beforeSleep);
await sleep(0);
steps.push(Step.afterSleep);

// Manual sleep to wait 2 ticks
for (let i = 0; i < 2; i++) {
await new Promise((r) => setTimeout(r, 0));
}

expect(steps).to.deep.equal(
[
// Sync execution
Step.beforeSleep,
// Next tick, first registered callback
Step.setTimeout0,
// Next tick, second registered callback
Step.afterSleep,
],
"Wrong steps"
);
});
});