variable-interval
v1.0.3
Published
module to schedule functions at variable time
Downloads
3
Maintainers
Readme
Module to schedule a function to be invoked after a variable time, chosen on the fly.
✨ Demo
Install
npm i -s variable-interval
Usage
// We are going to implement exponential backoff.
const {
setVariableInterval,
clearVariableInterval,
} = require("variable-interval");
// invocationCount is count of how many times
// the function has been called, starting from 1.
async function makeRequest(invocationCount) {
// Take the action
// await makeApiRequest(state.url);
}
function getWaitTime(invocationCount) {
if (invocationCount === 10) {
// Negative value stops the interval
return -1;
}
// The return value is the next wait time
return Math.pow(2, invocationCount);
}
const intervalId = setVariableInterval(makeRequest, getWaitTime);
// You can also clear the interval manually
// Clearing the interval after 20 secs.
setTimeout(() => clearVariableInterval(intervalId), 20 * 1000);
API
setVariableInterval(exec, next, ...params)
This function schedule exec
to be executed after time returned from the next
function.
exec: the function to be executed after each interval expires.
next: the function that returns the time after which next call to exec will be made. A negative return value terminates the interval.
params: any extra parameters passed would be passed to both exec and next.
Returns the intervalId
(string) that can be used with clearVariableInterval
the first parameter for both exec and next is the count of how many times they have been called
setVariableInterval(intervalId)
This function will stop the scheduling of exec
right away.
- intervalId: the intervalId obtained from
setVariableInterval
Maintainer
👤 Akarshit Wal
- Twitter: @akarshitwal
- Github: @akarshit
- LinkedIn: @akarshit-wal
Thanks to @akshendra for his inputs.
Show your support
Give a ⭐️ if this project helped you!