DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on • Edited on

Day 24: Async vibes

Today will feel the async vibes! ⏰ with custom timer implementation

Question

Implement polyfill function that simulates the setTimeout using callbacks.

window.mySetTimeout = function(callback, delay) {
  // Todo add your code
};

function delayedFunction() {
  console.log("Delayed function executed");
}

console.log("Start");
mySetTimeout(delayedFunction, 1000);
// Delayed function will be called after approximately 1000ms
console.log("End");
Enter fullscreen mode Exit fullscreen mode

NOTE: 🤔 Attempting epic advanced-level question. Failure? Nah, fun exploration! Feel the process!😂

Check the comment below to feel more. 🤣🤣🤣

Top comments (3)

Collapse
 
dhrn profile image
Dharan Ganesan • Edited

Hope this magic helps

(() => {
  const timers = {};

  const generateNewId = () => {
    let newId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
    while (timers.hasOwnProperty(newId)) {
      newId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);
    }
    return newId;
  };

  const check = () => {
    const currentTime = Date.now();
    for (const timerId in timers) {
      if (timers.hasOwnProperty(timerId) && currentTime > timers[timerId].time) {
        timers[timerId].callback();
        myClearTimeout(timerId);
      }
    }
    requestIdleCallback(check);
  };

  window.mySetTimeout = (callback, delay) => {
    if (typeof callback !== 'function') {
      throw new Error("Callback should be a function");
    }
    if (typeof delay !== 'number' || delay < 0) {
      throw new Error("Delay should be a positive number");
    }

    const newId = generateNewId();
    timers[newId] = {
      callback,
      time: Date.now() + delay
    };
    return newId;
  };

  window.myClearTimeout = (id) => {
    if (timers.hasOwnProperty(id)) {
      delete timers[id];
    }
  };

  requestIdleCallback(check);
})();
Enter fullscreen mode Exit fullscreen mode
Collapse
 
_bkeren profile image
''

where's requestIdCallback definition

Collapse
 
dhrn profile image
Dharan Ganesan

requestIdCallback taken from window or global object.

MDN: The window.requestIdleCallback() method queues a function to be called during a browser's idle periods.