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.
npm install interactivity-api-helpersMuch 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 usesetTimeoutinstead 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.
<div
data-wp-interactive="interval"
data-wp-context='{ "count": 0 }'
data-wp-init="init">
<p data-wp-text="context.count"></p>
</div>import { store, getContext } from '@wordpress/interactivity';
import { interval } from 'interactivity-api-helpers';
store('interval', {
init() {
const clearFn = interval(({ iteration, cancel, elapsed }) => {
const context = getContext();
context.count = iteration;
if (iteration === 4) cancel();
}, 1000);
},
});