simple-timeout
v0.1.9
Published
Simple timeout for easy handling in Node.js developed in TypeScript.
Downloads
6
Readme
simple-timeout
Simple, intuitive, timeout library. Easy to use, not a simple promise wrapper, not overloaded with fancy utilities.
Getting Started
npm install simple-timeout
Usage
// Initialization
const timeout = new Timeout(5000);
// On trigger
timeout.subscribe().then(() => {
// your code here
})
// Clear
timeout.clear()
Timeout options
const timeout = new Timeout(5000, timeoutOptions)
- timeoutMessage (optional) : System Out message when timeout is triggered.
- callbackFn (optional): Callback function called when the timeout is triggered.
status
andtimeoutMessage
are accessible via the arguments of the callback function.
const timeout = new Timeout(5000, {
callbackFn: ({ status, timeoutMessage }) => {
// Your code here
}
})
const timeout_two = new Timeout<number>(2000, (args) => (args.status === 'triggered') ? 1 : 2);
- nullSubscription (optional): Setting it to true make the
timeout.subscribe()
returnnull
when the timeout is cleared.
Note: When you provide the
callbackFn
in thetimeoutOptions
, it internally subscribes to the promise and provides the callback function to thethen
block. It is a shorthand fortimeout.subscribe().then(() => {})
Timeout Status
Status = 'unset' | 'set' | 'cleared' | 'triggered'
console.log(timeout.status) // Gives the current status of the timeout
unset
is the default state.- Timeout status is switched to
set
when it is initialized. triggered
is set when the timeout is triggered.cleared
is set when timeout is cleared.
Timeout Subscribe
timeout.subscribe()
.then(({status, timeoutMessage}) => {
// your code here
})
Returns a promise wrapper on setTimeout
.
Timeout Clear
timeout.clear()
// OR
timeout.clear(({status, timeoutMessage}) => {})
Clears the timeout. It takes an optional callback function as an argument.
Motivation
The idea for the library came about while I was working on a data gathering project that relies on scraping. For normal usage
Puppeteer timeouts would suffice, but I kept on running into some advanced cases where I had to use native timeouts. Unfortunately,
managing the native timeouts was a pain in the a** to deal with. Hence, this simple-timeout
was the solution to the problem I was facing.
I decided to separate it from the main project and make it into a library when I had other use cases for it. This library will be maintained
as long as it's parent project is maintained.
PRs are welcome
Feel free to raise Issues and PRs addressing bugfixes. I don't plan for this project to be too bloated with features.
License
Licensed under the MIT. See the LICENSE file for details.