This is my attempt so far:
The problem is, incrementation of "i" happens so fast that the variable "i" becomes equal to the variable "future" even before a second has passed.
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);
What other thing can I do rather than incrementing the value of i?
Hey man, how are you?
You may try to call Date.now() on every tick within while loop and check against your target value like so:
var td = {
"setTimeout": function (callback, ms) {
var dt = new Date();
var i = dt.getTime();
var future = i + ms;
while(Date.now() <= future) {
//do nothing - blocking
}
return callback();
}
};
Marco Alka
Software Engineer, Technical Consultant & Mentor
There is a really bad problem:
setTimeout()is async, but yourwhileloop is blocking. While Daniel posted the right answer to your date problem, you will still have trouble with the async nature. You will not get around that problem, sincesetTimeout()is coupled with the interpreter's event-loop; something you do not have access to.