Skip to content

Commit

Permalink
sleep(0) must yield event loop
Browse files Browse the repository at this point in the history
  • Loading branch information
dapplion committed May 7, 2022
1 parent fe52e43 commit b532a17
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
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"
);
});
});

0 comments on commit b532a17

Please sign in to comment.