UNPKG

@studiometa/js-toolkit

Version:

A set of useful little bits of JavaScript to boost your project! 🚀

55 lines (54 loc) • 1.16 kB
import { AbstractService } from "./AbstractService.js"; import { domScheduler } from "../utils/scheduler.js"; import { isFunction } from "../utils/is.js"; class RafService extends AbstractService { /** * @private */ isTicking = false; /** * @private */ scheduler = domScheduler; props = { time: performance.now(), delta: 0 }; trigger(props) { for (const callback of this.callbacks.values()) { this.scheduler.read(() => { const render = callback(props); if (isFunction(render)) { this.scheduler.write(() => { render(props); }); } }); } } loop() { const time = performance.now(); this.props.delta = time - this.props.time; this.props.time = time; this.trigger(this.props); if (!this.isTicking) { return; } requestAnimationFrame(() => this.loop()); } init() { this.isTicking = true; requestAnimationFrame(() => this.loop()); } kill() { this.isTicking = false; } } function useRaf() { return RafService.getInstance(); } export { RafService, useRaf }; //# sourceMappingURL=RafService.js.map