util_task_repeating_task.js

import Task from "./task.js";

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

/**
 * @class
 * @extends Task
 * Task that runs repeatedly based on a timer.
 */
class RepeatingTask extends Task {
    /**
     * Create a new repeating task.
     * @param {function} before Function to run upon adding to the task manager
     * @param {function} during Function to run during each completion of the timer
     * @param {function} after Function to run after full completion
     * @param {boolean} runOnAdd Whether to run the "during" function upon adding to the task manager
     * @param {number} delay Delay between firing the "during" function
     * @param {number} count Amount of times to wait and fire
     * @constructor
     */
    constructor({
        before = () => {},
        during = () => {},
        after = () => {},
        runOnAdd = false,
        delay = 1,
        count = -1
    }) {
        super();

        this._runOnAdd = runOnAdd;
        this._delay = delay;

        this._timer = 0;

        this._counter = 0;
        this._count = count;

        this._before = before;
        this._during = during;
        this._after = after;

        this._firstRun = false;
    }

    init() {
        if (this._runOnAdd) {
            this._before(this);
            this._during(this);
        }
    }

    update(elapsed) {
        if (!this._firstRun && !this._runOnAdd && this._counter === 0 && this._timer === 0) {
            this._before(this);
            this._firstRun = true;
        }

        this._timer += elapsed;
        if (this._timer >= this._delay) {
            this._during(this);
            this._counter++;
            if (this._count > 0 && this._counter >= this._count) {
                this._after(this);
                this._done = true;
            }

            this._timer = 0;
        }
    }
}

export default RepeatingTask;