All files / src task-loop.js

77.27% Statements 17/22
62.5% Branches 5/8
71.43% Functions 5/7
77.27% Lines 17/22

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 61 62 63 64 65 66 67 68 69 70 71 72 73 74        99x   99x 99x                             4x               1x 1x 1x                 2x 1x 1x 1x   1x                 1x 1x 1x 1x     1x                        
import EventHandler from './event-handler';
 
export default class TaskLoop extends EventHandler {
  constructor (hls, ...events) {
    super(hls, ...events);
 
    this._tickInterval = null;
    this._tickCallCount = 0;
  }
 
  /**
   * @override
   */
  destroy () {
    this.clearInterval();
    super.destroy();
  }
 
  /**
   * @returns {boolean}
   */
  hasInterval () {
    return this._tickInterval !== null;
  }
 
  /**
   * @param {number} millis Interval time (ms)
   * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
   */
  setInterval (millis) {
    Eif (!this._tickInterval) {
      this._tickInterval = setInterval(this.tick.bind(this, false), millis);
      return true;
    }
    return false;
  }
 
  /**
   * @returns {boolean} True when interval was cleared, false when none was set (no effect)
   */
  clearInterval () {
    if (this._tickInterval) {
      clearInterval(this._tickInterval);
      this._tickInterval = null;
      return true;
    }
    return false;
  }
 
  /**
   *
   * @param {Wether to force async} forceAsync
   * @returns {boolean} True when async, false when sync
   */
  tick () {
    this._tickCallCount++;
    Eif (this._tickCallCount === 1) {
      this.doTick();
      Iif (this._tickCallCount > 1)
        setTimeout(this.tick.bind(this), 0);
 
      this._tickCallCount = 0;
    }
  }
 
  /**
   * For subclass to implement task logic
   * @abstract
   */
  doTick () {
    throw new Error('TaskLoop is abstract and `doLoop` must be implemented');
  }
}