@cdellacqua/sleep
Advanced tools
Comparing version 2.0.0 to 3.0.0
@@ -0,21 +1,34 @@ | ||
import { HastyPromise } from 'hasty-promise'; | ||
export declare type TimeoutIdentifier = string | number | boolean | symbol | bigint | object | null; | ||
export declare type SleepConfig<T extends TimeoutIdentifier> = { | ||
setTimeout: (callback: () => void, ms: number) => T; | ||
clearTimeout: (timeoutId: T) => void; | ||
}; | ||
/** | ||
* A Promise containing a skip method. | ||
* Return a Promise that resolves after the specified delay. | ||
* | ||
* The returned Promise provides a `hurry` method that can | ||
* be used to resolve or reject early. Calling `hurry` without | ||
* any parameter will resolve the promise, while calling it with | ||
* an Error instance will reject it with the given Error. | ||
* | ||
* This overload takes an `overrides` object as its second parameter | ||
* containing custom setTimeout and clearTimeout functions. This | ||
* can be useful in tests or in scenarios where you would want | ||
* to use more precise timing than what setTimeout can offer. | ||
* | ||
* Note: if the delay is 0 the returned Promise will be already resolved. | ||
* | ||
* @param ms a delay in milliseconds. | ||
* @param overrides an object containing custom setTimeout and clearTimeout functions. | ||
* @returns a {@link HastyPromise} | ||
*/ | ||
export declare type SleepPromise = Promise<void> & { | ||
/** | ||
* Skip the specified timeout by resolving early. | ||
*/ | ||
skip(): void; | ||
/** | ||
* Skip the specified timeout by rejecting early. | ||
* | ||
* @param err (optional) the rejection reason. | ||
*/ | ||
abort(err?: unknown): void; | ||
}; | ||
export declare function sleep<T extends TimeoutIdentifier>(ms: number, overrides: SleepConfig<T>): HastyPromise<void, Error | void>; | ||
/** | ||
* Return a Promise that resolves after the specified delay. | ||
* | ||
* The returned Promise provides a `skip` method that can | ||
* be used to resolve (or reject) early. | ||
* The returned Promise provides a `hurry` method that can | ||
* be used to resolve or reject early. Calling `hurry` without | ||
* any parameter will resolve the promise, while calling it with | ||
* an Error instance will reject it with the given Error. | ||
* | ||
@@ -29,4 +42,4 @@ * Note: although using setTimeout under the hood, you can pass a value greater than | ||
* @param ms a delay in milliseconds. | ||
* @returns a {@link SleepPromise} | ||
* @returns a {@link HastyPromise} | ||
*/ | ||
export declare const sleep: (ms: number) => SleepPromise; | ||
export declare function sleep(ms: number): HastyPromise<void, Error | void>; |
@@ -0,1 +1,13 @@ | ||
function makeHastyPromise(executor) { | ||
const contextRef = {}; | ||
const basePromise = new Promise((res, rej) => { | ||
contextRef.hurryHandler = executor(res, rej); | ||
}); | ||
basePromise.hurry = (reason) => { | ||
var _a; | ||
(_a = contextRef.hurryHandler) == null ? void 0 : _a.call(contextRef, reason); | ||
contextRef.hurryHandler = void 0; | ||
}; | ||
return basePromise; | ||
} | ||
const maxSupportedTimeout = 2147483647; | ||
@@ -12,37 +24,35 @@ const patchedSetTimeout = (callback, ms, timeoutContext) => { | ||
const patchedClearTimeout = (timeoutContext) => clearTimeout(timeoutContext.id); | ||
const noop = () => void 0; | ||
const sleep = (ms) => { | ||
function sleep(ms, overrides) { | ||
const normalizedMs = Math.max(0, Math.ceil(ms)); | ||
const config = overrides ? overrides : { | ||
setTimeout: patchedSetTimeout, | ||
clearTimeout: patchedClearTimeout | ||
}; | ||
if (normalizedMs === 0) { | ||
const promise2 = Promise.resolve(); | ||
promise2.skip = noop; | ||
const promise2 = makeHastyPromise((res) => { | ||
res(); | ||
return () => void 0; | ||
}); | ||
return promise2; | ||
} | ||
let id; | ||
let resolve = noop; | ||
let reject = noop; | ||
const promise = new Promise((res, rej) => { | ||
resolve = res; | ||
reject = rej; | ||
id = patchedSetTimeout(() => { | ||
const promise = makeHastyPromise((res, rej) => { | ||
id = config.setTimeout(() => { | ||
id = void 0; | ||
resolve(); | ||
res(); | ||
}, normalizedMs); | ||
return (reason) => { | ||
if (id !== void 0) { | ||
config.clearTimeout(id); | ||
id = void 0; | ||
if (reason !== void 0) { | ||
rej(reason); | ||
} else { | ||
res(); | ||
} | ||
} | ||
}; | ||
}); | ||
promise.skip = () => { | ||
if (id !== void 0) { | ||
patchedClearTimeout(id); | ||
id = void 0; | ||
resolve(); | ||
} | ||
}; | ||
promise.abort = (err) => { | ||
if (id !== void 0) { | ||
patchedClearTimeout(id); | ||
id = void 0; | ||
reject(err); | ||
} | ||
}; | ||
return promise; | ||
}; | ||
} | ||
export { sleep }; |
@@ -1,1 +0,1 @@ | ||
(function(i,o){typeof exports=="object"&&typeof module!="undefined"?o(exports):typeof define=="function"&&define.amd?define(["exports"],o):(i=typeof globalThis!="undefined"?globalThis:i||self,o(i.sleep={}))})(this,function(i){"use strict";const o=2147483647,l=(s,d,e)=>(e=e||{id:void 0},d>o?e.id=setTimeout(l,o,s,d-o,e):e.id=setTimeout(s,d),e),f=s=>clearTimeout(s.id),n=()=>{},c=s=>{const d=Math.max(0,Math.ceil(s));if(d===0){const t=Promise.resolve();return t.skip=n,t}let e,r=n,u=n;const p=new Promise((t,v)=>{r=t,u=v,e=l(()=>{e=void 0,r()},d)});return p.skip=()=>{e!==void 0&&(f(e),e=void 0,r())},p.abort=t=>{e!==void 0&&(f(e),e=void 0,u(t))},p};i.sleep=c,Object.defineProperty(i,"__esModule",{value:!0}),i[Symbol.toStringTag]="Module"}); | ||
(function(n,t){typeof exports=="object"&&typeof module!="undefined"?t(exports):typeof define=="function"&&define.amd?define(["exports"],t):(n=typeof globalThis!="undefined"?globalThis:n||self,t(n.sleep={}))})(this,function(n){"use strict";function t(r){const i={},e=new Promise((d,o)=>{i.hurryHandler=r(d,o)});return e.hurry=d=>{var o;(o=i.hurryHandler)==null||o.call(i,d),i.hurryHandler=void 0},e}const s=2147483647,c=(r,i,e)=>(e=e||{id:void 0},i>s?e.id=setTimeout(c,s,r,i-s,e):e.id=setTimeout(r,i),e),a=r=>clearTimeout(r.id);function m(r,i){const e=Math.max(0,Math.ceil(r)),d=i||{setTimeout:c,clearTimeout:a};if(e===0)return t(l=>(l(),()=>{}));let o;return t((u,l)=>(o=d.setTimeout(()=>{o=void 0,u()},e),f=>{o!==void 0&&(d.clearTimeout(o),o=void 0,f!==void 0?l(f):u())}))}n.sleep=m,Object.defineProperty(n,"__esModule",{value:!0}),n[Symbol.toStringTag]="Module"}); |
@@ -5,3 +5,3 @@ { | ||
"description": "Delay execution using Promises.", | ||
"version": "2.0.0", | ||
"version": "3.0.0", | ||
"type": "module", | ||
@@ -56,3 +56,3 @@ "types": "dist/index.d.ts", | ||
"@types/node": "^16.11.10", | ||
"@typescript-eslint/eslint-plugin": "^5.4.0", | ||
"@typescript-eslint/eslint-plugin": "^5.29.0", | ||
"c8": "^7.11.3", | ||
@@ -70,8 +70,11 @@ "chai": "^4.3.4", | ||
"rimraf": "^3.0.2", | ||
"ts-node": "^10.4.0", | ||
"ts-node": "^10.8.1", | ||
"typedoc": "^0.22.17", | ||
"typedoc-plugin-markdown": "^3.12.1", | ||
"typescript": "^4.3.2", | ||
"typescript": "^4.7.4", | ||
"vite": "^2.6.4" | ||
}, | ||
"dependencies": { | ||
"hasty-promise": "^1.0.0" | ||
} | ||
} |
@@ -46,3 +46,3 @@ # @cdellacqua/sleep | ||
const sleepPromise = sleep(1000); | ||
setTimeout(() => sleepPromise.skip(), 500); | ||
setTimeout(() => sleepPromise.hurry(), 500); | ||
await sleepPromise; | ||
@@ -60,3 +60,3 @@ console.log('see you in half a sec!'); | ||
const sleepPromise = sleep(1000); | ||
setTimeout(() => sleepPromise.abort('ops!'), 500); | ||
setTimeout(() => sleepPromise.hurry(new Error('ops!')), 500); | ||
try { | ||
@@ -69,1 +69,16 @@ await sleepPromise; | ||
``` | ||
Use custom setTimeout/clearTimeout implementation: | ||
```ts | ||
import {sleep} from '@cdellacqua/sleep'; | ||
async function example() { | ||
const sleepPromise = sleep(1000, { | ||
setTimeout: (callback, ms) => setTimeout(callback, ms * 10), | ||
clearTimeout: (timeoutId) => clearTimeout(timeoutId), | ||
}); | ||
await sleepPromise; | ||
console.log('see you in... 10 seconds?'); | ||
} | ||
``` |
Sorry, the diff of this file is not supported yet
Deprecated
MaintenanceThe maintainer of the package marked it as deprecated. This could indicate that a single version should not be used, or that the package is no longer maintained and any new vulnerabilities will not be fixed.
Found 1 instance in 1 package
10079
108
82
1
1
+ Addedhasty-promise@^1.0.0
+ Addedhasty-promise@1.0.0(transitive)