Skip to content

Commit

Permalink
feat: delay function
Browse files Browse the repository at this point in the history
Changelog: feature
  • Loading branch information
mrspartak committed Jun 21, 2024
1 parent 9934701 commit a1a233e
Show file tree
Hide file tree
Showing 11 changed files with 120 additions and 3 deletions.
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,19 @@ const [apiError, status] = await to(api.post("/me/status", { status: "online" })
if (apiError) {
// Handle error
}
```

### `delay` Pause Execution for a Specified Time

The delay function pauses the execution of your code for a specified number of milliseconds. This can be useful in various scenarios, such as waiting for an operation to complete, introducing a delay between retries, or simply pausing execution for debugging purposes.

```ts
import { delay } from "@mrspartak/promises"
import { parsePage } from "./parser"

for (let i = 0; i < 10; i++) {
// Parse the page and wait for 1 second before parsing the next page
const pageData = await parsePage(i)
await delay(1000)
}
```
8 changes: 8 additions & 0 deletions examples/delay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { delay } from "@mrspartak/promises"
import { parsePage } from "./parser"

for (let i = 0; i < 10; i++) {
// Parse the page and wait for 1 second before parsing the next page
const pageData = await parsePage(i)
await delay(1000)
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
},
"devDependencies": {
"@biomejs/biome": "1.8.0",
"@types/web": "^0.0.149",
"@vitest/coverage-v8": "^1.6.0",
"agadoo": "^3.0.0",
"cross-env": "^7.0.3",
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 26 additions & 0 deletions src/delay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Pauses execution for a specified number of milliseconds.
*
* @param {number} ms - The number of milliseconds to delay execution.
* @returns {Promise<void>} A promise that resolves after the specified delay.
* @throws {Error} Thrown if the input is not a number or if the number is negative.
*
* @includeExample examples/delay.ts
*/
export async function delay(ms: number): Promise<void> {
// Validate that the input is a number
if (typeof ms !== 'number') {
throw new Error('delay(ms) requires a number as a parameter');
}

// Validate that the number is positive
if (ms < 0) {
throw new Error('delay(ms) requires a positive number as a parameter');
}

// Return a promise that resolves after the specified delay
return new Promise((resolve) => setTimeout(resolve, ms));
}

// Alias for delay: sleep
export const sleep = delay;
3 changes: 2 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { to } from "./to";
import { delay, sleep } from "./delay";

export { to };
export { to, delay, sleep };
3 changes: 2 additions & 1 deletion src/types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from '../index'
export * from '../index'
export * from './web-types'
1 change: 1 addition & 0 deletions src/types/web-types.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="web" />
14 changes: 14 additions & 0 deletions test/build/delay.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { describe, expect, it } from "vitest";
import { delay, sleep } from '../../dist/index.js'

describe("delay", () => {
it("must be a function", () => {
expect(typeof delay).toBe("function");
});
});

describe("sleep", () => {
it("must be a function", () => {
expect(typeof sleep).toBe("function");
});
});
42 changes: 42 additions & 0 deletions test/src/delay.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vitest";
import { delay, sleep } from '../../src/delay.js'

describe('delay', () => {
it('should be a function', () => {
expect(typeof delay).toBe('function')
})

it('should return a promise', () => {
expect(delay(1) instanceof Promise).toBe(true)
})

it('should resolve after the specified delay', async () => {
const start = Date.now()
await delay(100)
const end = Date.now()
expect(end - start).toBeGreaterThanOrEqual(100)
})

it('should throw an error if the input is not a number', async () => {
// @ts-ignore
await expect(delay('test')).rejects.toThrow('delay(ms) requires a number as a parameter')
})

it('should throw an error if the number is negative', async () => {
await expect(delay(-1)).rejects.toThrow('delay(ms) requires a positive number as a parameter')
})

it('should not throw an error if the number is zero', async () => {
await expect(delay(0)).resolves.toBeUndefined()
})
})

describe('sleep', () => {
it('should be a function', () => {
expect(typeof sleep).toBe('function')
})

it('should return a promise', () => {
expect(sleep(1) instanceof Promise).toBe(true)
})
})
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@
"lib": ["ES2018"]
},
"include": ["./src/**/*"],
"exclude": ["node_modules", "examples", "dist"]
"exclude": ["node_modules", "examples", "dist"],
"typeRoots": ["src/types", "./node_modules/@types"]
}

0 comments on commit a1a233e

Please sign in to comment.