
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? ...
