0.3.1 • Published 1 year ago
interactivity-api-helpers v0.3.1
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-helpersUsage
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: If- true, the interval will use- setTimeoutinstead of- requestAnimationFrame. Default is- false.
- precise: While- true, the interval will try to be as precise as possible by accounting for the time it last ran- Δt. Default is- true.
 
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);
  },
});