Repository

js/Mobilizing/time/Timer.js

import Component from '../core/Component';
import * as debug from '../core/util/Debug';

/**
*A timer is a time manager that gives the possibily to schedule a function every <i>n</i> ms.
*/
export default class Timer extends Component {
    /**
     * @param {Object} params Parameters object, given by the constructor.
     * @param {Number} params.interval the number of millisecond to wait before the next timer's fire
     * @param {Function} params.callback the function to fires every time the timer's interval is passed. Can be an anonymous fonction or not.
     * @example
     *   let myTimer = new Mobilizing.Timer({
           "interval": 200,
           "callback": function(){
             //your code here
           }
         });
     *   myTimer.start();
     */
    constructor({
        interval = 100,
        callback = null,
    } = {}) {
        super(...arguments);

        this.interval = interval;
        this.callback = callback;
    }

    /**
    * Setup the timer with the current time
    */
    setup() {
        super.setup(); //for chainning

        this.startTime = performance.now();
        this.currentTime = performance.now();
        this.running = false;
    }

    /**
    * Deactivate the component
    */
    off() {
        super.off();
        this.stop();
    }

    /**
    * Starts the timer
    */
    start() {
        if (this.active) {
            this.reset();
            this.running = true;
        }
        else {
            debug.info("component is off");
        }
    }

    /**
    * Stop the timer
    */
    stop() {
        this.startTime = 0;
        this.currentTime = 0;
        this.running = false;
    }

    /**
    * Updates the timer's state
    */
    update() {
        if (this.active && this.running) {

            this.currentTime = performance.now();
            const tempInterval = this.currentTime - this.startTime;

            if (tempInterval >= this.interval) {
                this.callback();
                this.reset();
            }
        }

    }

    /**
    * Resets the timer
    * @method reset
    */
    reset() {
        this.startTime = performance.now();
        this.currentTime = performance.now();
    }
}