All files precision.mjs

50.81% Statements 31/61
100% Branches 4/4
42.85% Functions 3/7
50.81% Lines 31/61

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 611x 1x 1x 1x 1x 2x 2x 2x 2x 2x 1x 1x                   1x 1x                                 1x 1x     1x 1x 3x 3x 1x 1x 2x 2x 2x 1x 1x       1x 1x 1x 1x
 
 
 
class PrecisionTimer {
    constructor() {
        this.frameInterval = 0.0;
        this.setFramerate(30);
        this.timerRunning = false;
        this.lastFrameTime = performance.now();
    }
 
    start(callback) {
        if (this.timerRunning) {
            return; // Already running - Start gate
        }
        this.timerRunning = true;
        this.lastFrameTime = performance.now();

        this._pollingTick(callback);
         
    }
 
    _pollingTick(callback) {
        if(!this.timerRunning) {
            return; // Stop gate
        }

        // key up the next tick
        setTimeout(() => {
                this._pollingTick(callback);
        }, (this.frameInterval));

        const currentTime = performance.now();
        const elapsedMs = currentTime - this.lastFrameTime;
        callback(elapsedMs);        
        const runTime = performance.now() - currentTime;
        this.lastFrameTime = currentTime;

    }
    
    stop() {
        this.timerRunning = false;
    }
 
    now() {
        return performance.now();
    }
 
    setFramerate(fps) {
        this.framerate = fps;
        this.frameInterval = 1000 / this.framerate;
    }
    
    static roundTo(value, decimals) {
        const factor = Math.pow(10, decimals);
        return Math.round(value * factor) / factor;
    }
}
 
 
export default PrecisionTimer;