/*
 * This is basically an implementation of the requestIdleCallback native
 * method.
 *
 * Originally committed in cbc7a9c7ee
 */
import run from 'ember-runloop';

let idleWaiterCount = 0;

export default function requestIdleCallback(callback) {
  idleWaiterCount++;
  let previousTime = new Date();
  function tryForIdle() {
    let currentTime = new Date();
    /* If the last frame was within X ms, run the callback */
    if (currentTime - previousTime < 24) {
      idleWaiterCount--;
      run(null, callback);
    } else {
      previousTime = currentTime;
      requestAnimationFrame(tryForIdle);
    }
  }
  requestAnimationFrame(tryForIdle);
}

export function getIdleWaiterCount() {
  return idleWaiterCount;
}
