Skip to content

Commit

Permalink
feat(js-core): sleep() now accepts a unit of time
Browse files Browse the repository at this point in the history
  • Loading branch information
ersimont committed Aug 20, 2022
1 parent 1544c92 commit cd3ac16
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 4 deletions.
13 changes: 13 additions & 0 deletions projects/js-core/src/lib/time/sleep.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { fakeAsync, tick } from '@angular/core/testing';
import { sleep } from './sleep';
import { TimeUnit } from './time-utils';

describe('sleep()', () => {
it('resolves after the given delay', fakeAsync(() => {
Expand All @@ -13,4 +14,16 @@ describe('sleep()', () => {
tick(1);
expect(resolved).toBe(true);
}));

it('accepts units for the delay', fakeAsync(() => {
let resolved = false;
sleep(10, TimeUnit.Seconds).then(() => {
resolved = true;
});

tick(9_999);
expect(resolved).toBe(false);
tick(1);
expect(resolved).toBe(true);
}));
});
14 changes: 10 additions & 4 deletions projects/js-core/src/lib/time/sleep.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import { convertTime } from './time-utils';

/**
* Returns a promise that resolves after `ms` milliseconds.
* Returns a promise that resolves after a specified delay.
*
* @param unit Can be anything listed in the docs for {@link TimeUnit}. Defaults to milliseconds
*
* ```ts
* // do something
* await sleep(1000); // wait a second
* await sleep(1_000); // wait 1 second

This comment has been minimized.

Copy link
@RaphiStein

RaphiStein Aug 25, 2022

TIL about the numeric separator syntax. Cool!

* // do something else
* await sleep(2, 'hours'); // wait 2 hours
* // do a final thing
* ```
*/
export async function sleep(ms: number): Promise<undefined> {
export async function sleep(delay: number, unit = 'ms'): Promise<undefined> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
setTimeout(resolve, convertTime(delay, unit, 'ms'));
});
}

0 comments on commit cd3ac16

Please sign in to comment.