Polyfill of setTimeout

const createSetTimeout = () => {
  let timerId = 0;
  let timerMap = {};

  const setTimeoutPolyfill = (callback, delay, ...args) => {
    let id = timerId++;
    timerMap[id] = true;
    let start = Date.now();

    function trackTimeout() {
      if (!timerMap[id]) return;
      if (Date.now() > start + delay) {
        callback.apply(this, args);
      } else {
        requestIdleCallback(trackTimeout);
      }
    }
    // make it async
    requestIdleCallback(trackTimeout);
    return id;
  };

  const clearTimeoutPolyfill = (id) => {
    delete timerMap[id];
  };

  return { setTimeoutPolyfill, clearTimeoutPolyfill };
};

const { setTimeoutPolyfill, clearTimeoutPolyfill } = createSetTimeout();

console.log("Start");
setTimeoutPolyfill(
  (name) => {
    console.log("Set Timeout Polyfill");
    console.log(name);
  },
  1000,
  "Arjunan K"
);
console.log("End");

// Output:
Start
End
Set Timeout Polyfill
Arjunan K