import {
  TICK,
} from './ActionTypes';

class RunLoop {
  constructor() {
    this.store = null;
    this._listeners = [];

    let prev = Date.now();

    let runLoop = () => {
      const now = Date.now();
      const dt = now - prev;
      prev = now;

      this.store.dispatch({
        type: TICK,
        dt,
      });

      this._listeners.forEach((listener) => listener());

      window.requestAnimationFrame(runLoop);
    };

    this.unsetPlaybackRunLoop = () => {
      runLoop = () => {};
    };

    window.requestAnimationFrame(runLoop);
  }

  setStore(store) {
    this.store = store;
  }

  subscribe(listener) {
    this._listeners.push(listener);
  }

  unsubscribe(listener) {
    const idx = this._listeners.indexOf(listener);

    if (idx === -1) {
      throw new Error('tried to unsubscribe listener that wasn\'t subscribed');
    }

    this._listeners.splice(idx, 1);
  }
}

const runLoop = new RunLoop();

export default runLoop;

@@ -127,16 +127,24 @@
     
-let prev
+this._lastTickMs
  = D
@@ -163,32 +163,84 @@
     
-let runLoop = () =%3E %7B%0A  
+window.requestAnimationFrame(this._runLoop.bind(this));%0A  %7D%0A%0A  _runLoop() %7B%0A
     
@@ -267,18 +267,16 @@
 ();%0A    
-  
 const dt
@@ -288,24 +288,46 @@
 w - 
-prev;%0A      prev
+this._lastTickMs;%0A    this._lastTickMs
  = n
@@ -331,26 +331,24 @@
 = now;%0A%0A    
- 
- 
 this.store.d
@@ -363,18 +363,16 @@
 %7B%0A      
-  
 type: TI
@@ -375,18 +375,16 @@
 : TICK,%0A
-  
       dt
@@ -393,17 +393,13 @@
     
-  
 %7D);%0A%0A
-  
     
@@ -454,18 +454,16 @@
 );%0A%0A    
-  
 window.r
@@ -487,140 +487,32 @@
 ame(
-runLoop);%0A    %7D;%0A%0A    this.unsetPlaybackRunLoop = () =%3E %7B%0A      runLoop = () =%3E %7B%7D;%0A    %7D;%0A%0A    window.requestAnimationFrame(runLoop
+this._runLoop.bind(this)
 );%0A 

Clean up runloop now that it's always on