-2

I am trying to understand the async behaviour of Javascript, how can we implement in normal functions. For example below code I am trying to implement a custom SetTimeout function which would work asynchronously. It should call the function muCsutSetInterval and go the console.log("after");.

Please suggest the right way to do it. Appreciate your help..

var myCustSetInterval = function (time, callback){
    let initial = new Date();
    let current;
    while(true){
        current = new Date();
        if(current.getTime()-initial.getTime()===time){
            break;
        }
    }
    callback();
}

console.log("before");

myCustSetInterval(5000,()=>{
    console.log("Callback");
});

console.log("after");
user3846586
  • 43
  • 1
  • 8

1 Answers1

1

You cant write asynchronous javascript. However the javascript API provides internal functions (setTimeout, fetch) that behave asynchronously, which you can work with. So you need those async internal calls to actually write async code. E.g.:

function customSetTimeout(callback, ms, ...args) {
  const ends = Date.now() + ms;
  (function check() {
     if(new Date >= ends) {
       callback(...args);
     } else {
       setTimeout(check, 0); // <- the internal call
     }
  })()
}
rtn
  • 127,556
  • 20
  • 111
  • 121
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151