/**
 * @module tgam-patterns/request-interval
 */
export default {
  /**
   * @method setInterval
   * @description Behaves the same as setInterval except uses requestAnimationFrame() where possible for better performance
   * @param {Function} fn - The callback function
   * @param {Number} delay - The delay in milliseconds
   * @returns {Object} with `value`
   */
  setInterval: function(fn, delay) {
    if (!window.requestAnimationFrame) {
      return window.setInterval(fn, delay);
    }

    let start = new Date().getTime();
    let handle = {};

    function loop() {
      let current = new Date().getTime();
      let delta = current - start;

      if (delta >= delay) {
        fn.call();
        start = new Date().getTime();
      }

      handle.value = window.requestAnimationFrame(loop);
    }

    handle.value = window.requestAnimationFrame(loop);
    return handle;
  },

  /**
   * @method clearInterval
   * @description Behaves the same as clearInterval except uses cancelAnimationFrame() where possible for better performance
   * @param {Number|Object} handle - The callback function
   */
  clearInterval: function(handle) {
    window.cancelAnimationFrame ? window.cancelAnimationFrame(handle.value) : clearInterval(handle);
  }
};
