setTimeout JavaScript

How does setTimeout Work with the JavaScript Engine?

If one wants a function to be executed just after a period of time T in JavaScript, what do they do? They dump it in a setTimeout and surely, just immediately after T has elapsed, the function will be run. Right? Can you predict what happens when the code below is run? You should try it out in a Node.js REPL or the console. const extractTime = (date) => date.toTimeString().split(" ")[0]; var start = new Date(); console.log("starting at", extractTime(new Date())); // #1 setTimeout(() => { const time = extractTime(new Date()); console.log(`From setTimeout. Logged at ${time}`); // #2 }, 1000); while (new Date() - start < 3000) { // empty while loop } // #3 What I ordered vs What I got For anyone that has not worked with code like this before, the expectation would be that #2 will be logged about 1 second after #1, but it was not. It was logged about 3 seconds after #1. Why? ...

January 4, 2023 · 3 min · Orim Dominic Adah
Implement JavaScript's setInterval using setTimeout

Implement JavaScript's setInterval using setTimeout

I was in a job interview pair programming session where I was asked to implement JavaScript’s setInterval method without using setInterval itself. I did poorly at that interview for many reasons, including not knowing how to implement this. The Question Implement the setInterval function in such a way that executing new SetInterval.prototype.start will start the function passed to it and run the function at intervals interval milliseconds until the SetInterval.prototype.clear method is called. ...

June 23, 2021 · 3 min · Orim Dominic Adah