interactivity-api-helpers
v0.3.1
Published
Helper library for building with the WordPress Interactivity API
Downloads
9
Maintainers
Readme
Interactivity API Helpers
A collection of helper features for building with the WordPress Interactivity API.
WIP. Open an issue if you want to see a specific helper added.
Installation
npm install interactivity-api-helpers
Usage
interval(fn, timer, settings)
Much like the setInterval
function in JavaScript, this helper will call the provided function at a regular interval. This helper, however, will provide context to the store, and uses requestAnimationFrame
for better performance.
Takes the following parameters:
fn
: The function to call at each interval.timer
: The number of milliseconds to wait between each call.settings
:useTimeout
: Iftrue
, the interval will usesetTimeout
instead ofrequestAnimationFrame
. Default isfalse
.precise
: Whiletrue
, the interval will try to be as precise as possible by accounting for the time it last ranΔt
. Default istrue
.
The function provided to interval
will receive an object with the following properties:
cancel
: A function that can be called to cancel the interval.elapsed
: The number of milliseconds that have elapsed since the interval was started.iteration
: The number of times the interval has been called.
Returns a function that can be called to cancel the interval.
Example
<div
data-wp-interactive="interval"
data-wp-context='{ "count": 0 }'
data-wp-init="init">
<p data-wp-text="context.count"></p>
</div>
store('interval', {
init() {
const clearFn = interval(({ iteration, cancel, elapsed }) => {
const context = getContext();
context.count = iteration;
if (iteration === 4) cancel();
}, 1000);
},
});