Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/luckydrq/setinterval
More reasonable setInterval for async task
https://github.com/luckydrq/setinterval
setinterval timer utility
Last synced: 3 days ago
JSON representation
More reasonable setInterval for async task
- Host: GitHub
- URL: https://github.com/luckydrq/setinterval
- Owner: luckydrq
- Created: 2016-12-28T14:08:59.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2021-07-26T10:24:02.000Z (over 3 years ago)
- Last Synced: 2025-01-13T01:45:46.669Z (22 days ago)
- Topics: setinterval, timer, utility
- Language: JavaScript
- Homepage:
- Size: 10.7 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Changelog: History.md
Awesome Lists containing this project
README
# setinterval
[![NPM version][npm-image]][npm-url]
[![npm download][download-image]][download-url][npm-image]: https://img.shields.io/npm/v/setinterval.svg?style=flat-square
[npm-url]: https://npmjs.org/package/setinterval
[download-image]: https://img.shields.io/npm/dm/setinterval.svg?style=flat-square
[download-url]: https://npmjs.org/package/setintervalWe all know the drawbacks of the built-in `setInterval` in Node.js(actually js itself).
It's more reasonable to start measuring period after every async task gets done. So here it is.
## Install
`$ npm i setinterval`## Example
```js
const Timer = require('setinterval');
const t = new Timer(async () => {
const user = await db.User.get(id);
console.log(user);
}, 1000);// start timer
t.setInterval();// after some time...
// clear timer
t.clearInterval();
```## API
### new Timer(fn, period)
Timer constructor.
Params:
- fn(*required*): function executed after every `period`. Should be a Promise or async function or generator function or thunk.
- period(*required*): timer period(*units: milliseconds*).### setInterval([initialDelay], [invokeImmediate])
Start timer after a certain delay(defaults to *0*) and can decide if invoke immediately(defaults to *false*).
Params:
- initialDelay(*optional*): Delay period(*units: milliseconds*) before timer gets triggered. *default: 0*
- invokeImmediate(*optional*): specify if the timer function invoke immediately.*default: false*### clearInterval()
Stop timer(can be restart again).
## Events
### tick
Triggered each time fn is finished, whenever a error is thrown. You can cancel the timer in this event. A `count` parameter is passed in the event handler which stands for how many times fn has been called.
```js
timer.on('tick', count => {
timer.clearInterval();
});
```### error
Triggered when error thrown from fn.
```js
timer.on('error', e => {
logger.info(e.stack);
});
```## License
MIT