dynamic-interval
🕐 The dynamic setInterval
setInterval
with the ability to specify a new interval duration on each tick.
Also referred to as a "dynterval".
Sections
Install
npm install dynamic-interval
Usage
const dynterval =
Examples
Basic
This script doubles the duration of the interval on each iteration, starting with 50ms:
// you can attach arbitrary properties to this object (in this case, `rate`), but// `wait` is what's used to determine the duration between each intervalconst config = wait: 50 rate: 2 const dynterval = // interval { wait: 50, rate: 2 }// interval { wait: 100, rate: 2 }// interval { wait: 200, rate: 2 }// ... // clear out the interval after 2 seconds// NOTE: `window.clearInterval` is not compatible! use the `clear` method instead
Advanced
This script calculates the amount of drift on each step and corrects for it during the subsequent step.
It uses a custom interval api
. In this case, we're using worker-timers
.
const setAccurateInterval = { let expected = Date + wait return }
Interface
setDynterval(<action>, <wait|config>, <api>)
action
The callback to invoke on each interval tick
- Type:
Function
- Required
wait
Specifies the duration of each interval (i.e. the amount of time to wait between each tick)
- Type:
Number
config
Specifies the configuration of the interval. Passed into the action
function as context
.
-
Type:
Object
-
Properties:
-
wait
Specifies the duration of each interval
- Type:
Number
- Type:
-
immediate
Determines if the interval should start immediately or wait one interval before starting
- Type:
Boolean
- Default:
false
- Type:
-
api
A custom interval api
may be provided. It must define functions for both setInterval
and clearInterval
.
-
Type:
Object
-
Properties:
-
setTimeout
Defines how to create a new timeout
- Type:
Function
- Signature:
setTimeout(func: Function, delay: Number)
- Returns:
TimeoutID
- Default:
WindowOrWorkerGlobalScope.setTimeout
- Type:
-
clearTimeout
Defines how to clear or cancel a timeout
- Type:
Function
- Signature:
clearTimeout(id: TimeoutID)
- Returns:
void
- Default:
WindowOrWorkerGlobalScope.clearTimeout
- Type:
-
setInterval
Defines how to create a new interval
- Type:
Function
- Signature:
setInterval(func: Function, delay: Number)
- Returns:
IntervalID
- Default:
WindowOrWorkerGlobalScope.setInterval
- Type:
-
clearInterval
Defines how to clear or cancel an interval
- Type:
Function
- Signature:
clearInterval(id: IntervalID)
- Returns:
void
- Default:
WindowOrWorkerGlobalScope.clearInterval
- Type:
-
Related
stateful-dynamic-interval
adds pause, resume and grouping functionality todynamic-interval
.accurate-interval
an interval that automatically corrects for local drift on each tick. May be provided as anapi
.audio-context-timers
an interval that uses the Web Audio API clock. May be provided as anapi
.worker-timers
an interval that uses Service Workers as a backend. May be provided as anapi
.
License
MIT