util_task_frame_task.js

import Task from "./task.js";

/**
 * @module FrameTask
 * @fileoverview Contains FrameTask class.
 */

/**
 * @class
 * @extends Task
 * Task that is updated every frame.
 */
class FrameTask extends Task {
    /**
     * Create a new frame task.
     * @param {function} during Function to run every frame
     * @param {function} after Function to run after completion
     * @param {number} duration Total length to run in seconds (use -1 to never stop)
     */
    constructor({
        during = elapsed => {},
        after = () => {},
        duration = 1
    }) {
        super();

        this._timer = 0;
        this._duration = duration;

        this._during = during;
        this._after = after;
    }

    update(elapsed) {
        this._during(elapsed);

        if (this._duration >= 0) {
            this._timer += elapsed;
            if (this._timer >= this._duration) {
                this._after(this);
                this.stop();
            }
        }
    }
}

export default FrameTask;