/**
 * @module tgam-patterns/request-timeout
 */
export default {
  /**
   * @method setTimeout
   * @description Behaves the same as setTimeout 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`
   */
  setTimeout: function(fn, delay) {
    if (!window.requestAnimationFrame) {
      return window.setTimeout(fn, delay);
    }

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

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

      delta >= delay ? fn.call() : handle.value = window.requestAnimationFrame(loop);
    }

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

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