Tanmay
Tanmay

Reputation: 3159

Creating custom setTimeout() function

var td = {
setTimeout: function(callback, ms){
var dt = new Date();
    var i = dt.getTime(), future = i+ms;
    while(i<=future){
      if(i === future){
        callback();
      }
      // i = dt.getTime();
      i++;
  }
 }
};
td.setTimeout(function(){
    console.log("Hello"); // executes immediately
}, 3000);

The problem with this approach is that, at the end of the while block I am setting the value of i to i + 1 which I think, should be set to the current timestamp (dt.getTime()), that way, future (a timestamp value at which the callback function should execute) can be compared with the current timestamp, which is the value of i.

But when I comment out i++ and uncomment this line:

i = dt.getTime();

and run the script, the browser freezes. Is there a way to create a setTimout() method that would serve the same purpose as window.setTimeout()?

Upvotes: 1

Views: 2396

Answers (2)

The Bomb Squad
The Bomb Squad

Reputation: 4337

Behold.. setTimeout that isn't synchronous >:D

function timeout(fn,n){
  (async()=>{
    n=n||0; var time=Date.now()+n
    await new Promise(r=>r()) //asynchronous even if n is 0
    while(Date.now()<time){
      await new Promise(r=>r())
    }
    fn()
  })()
  return true
}

//demonstration
timeout(()=>console.log(3),200)
timeout(()=>console.log(2),20)
console.log(1)

Upvotes: 0

Maurice
Maurice

Reputation: 357

The problem with your code is, that dt.getTime() always returns the same value (namely the time when the dt object was created. To make this working, you need to do

dt = new Date();

before you set

i = dt.getTime();

Upvotes: 1

Related Questions