All files / src/raf raf-timer.ts

0% Statements 0/35
0% Branches 0/12
0% Functions 0/10
0% Lines 0/35

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 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214                                                                                                                                                                                                                                                                                                                                                                                                                                           
import * as mathf from '../mathf/mathf';
import * as time from '../time/time';
import {Raf} from './raf';
 
/**
 * A Raf based timer.  This class allows you to run RAF for only a
 * set duration and then stop.
 *
 * This can be useful to do things like one time animations.
 *
 * Here is an example of running the rafTimer for 300ms
 * and lerping the x value of the box.
 * ```ts
 * // Box x starting value.
 * box.x = 0;
 *
 * let rafTimer = new RafTimer((progress)=> {
 *   // Called on each raf cycle from when start is called
 *   // for 300ms.
 *
 *   // progress is passed as a value between 0 and 1.
 *   // console.log('progress')
 *
 *
 *   // Will move the box from 0 (starting) to 500
 *   // based on the progress.
 *   box.x = mathf.lerp(box.x, 500, progress);
 *
 *   // or go fancy and add easing to the progress!
 *   // box.x = mathf.ease(box.x, 500, progress, ease.easeInOutSine);
 * })
 *
 * rafTimer.onComplete(()=> {
 *   // Do something on completion.
 * })
 *
 * // Set the duration of the rafTimer 300 and start it.
 * rafTimer.setDuration(300);
 * rafTimer.play();
 *
 *
 * // If you want, slow down the FPS.
 * rafTimer.setFps(10);
 *
 * // Pause if you want.
 * window.setTimeout(()=> {
 *   rafTimer.pause();
 *
 *   // Start playing again from pause point
 *   playButton.addEventListner('click', ()=> {
 *     rafTimer.play();
 *   }, { once: true});
 *
 *   // Reset to beginning
 *   resetButton.addEventListner('click', ()=> {
 *     rafTimer.reset();
 *     rafTimer.play();
 *   }, { once: true});
 *
 * })
 *
 * TODO (uxder); Update this to extend emit emitter.
 *
 * ```
 */
export class RafTimer {
  private rafLoop: Function;
  private raf: Raf;
  private duration: number;
  private timeElapsed: number;
  private timeSnapshot: number;
  private playing: boolean;
  private completeCallback: Function | null;
  public progress: number;
 
  constructor(rafLoop: Function) {
    /**
     * The callback to be executed upon each request animation frame.
     * @type {Function}
     */
    this.rafLoop = rafLoop;
 
    /**
     * The internal raf instance
     * @type {private}
     */
    this.raf = new Raf(() => {
      this.animationLoop_();
    });
 
    /**
     * The internal raf instance
     * @type {private}
     */
    this.duration = 0;
 
    /**
     * The progress of the timer. The amount of percentage
     * we have elasped, represented in a number between 0-1.
     */
    this.progress = 0;
 
    /**
     * The amount of time in ms that has elapsed
     */
    this.timeElapsed = 0;
 
    /**
     * The last point in which time was measured.
     */
    this.timeSnapshot = 0;
 
    /**
     * Whether raf is active, we are playing .
     */
    this.playing = false;
 
    // A single complete callback.
    this.completeCallback = null;
  }
 
  /**
   * The internal animation loop.
   */
  private animationLoop_() {
    // In theory, when playing is false, this loop shouldn't
    // run but safe guard.
    if (!this.playing) {
      return;
    }
 
    // On each raf cycle, we want to calculate
    // the amount of time that has elapsed since
    // the last known timeSnapshot (when the time
    // was recorded).
    // We add this to the total value of time elapsed.
    const timeSinceLastTimeSnapshot = time.timeDiffMs(
      this.timeSnapshot,
      time.now()
    );
 
    this.timeElapsed += timeSinceLastTimeSnapshot;
 
    this.progress = mathf.clampAsPercent(this.timeElapsed / this.duration);
 
    // Update the snapshot.
    this.timeSnapshot = time.now();
 
    // If we aren't at 100% call the raf loop.
    if (this.progress < 1) {
      this.rafLoop && this.rafLoop(this.progress);
    } else {
      // Run the main update loop one more time as completion.
      this.rafLoop && this.rafLoop(1);
      // Complete
      this.reset();
      this.raf.stop();
      this.completeCallback && this.completeCallback(1);
    }
  }
 
  /**
   * Set the duration of the raf loop in ms.
   * @param duration  The duration in ms.
   */
  setDuration(duration: number): void {
    this.duration = duration;
  }
 
  /**
   * Sets the fps of raf loop..
   */
  setFps(fps: number): void {
    this.raf.setFps(fps);
  }
 
  onComplete(callback: Function) {
    this.completeCallback = callback;
  }
 
  /**
   * Start playing the rafTimer.
   */
  play(): void {
    if (this.playing) {
      return;
    }
    this.playing = true;
    this.timeSnapshot = time.now();
    this.raf.start();
  }
 
  /**
   *  Resets the RAF timer.
   */
  reset(): void {
    this.playing = false;
    this.raf.stop();
    this.timeElapsed = 0;
  }
 
  /**
   *  Pauses the raf Timer.
   */
  pause(): void {
    this.raf.stop();
    this.playing = false;
  }
 
  dispose() {
    this.raf.dispose();
  }
}