I'm trying to run some synchronous function which should wait for a certain time and then return control. But for some reason, it keeps executing asynchronously, or at least that's how it looks.
This is the code:
function pause(ms) {
var dt = new Date();
while (new Date() - dt <= ms) {
/* Do nothing */
}
}
console.log("start calculation..");
pause(3000);
console.log("calculation finished!");
this immediately shows the following in the console:
start calculation..
calculation finished!
There is no delay at all, as if the pause function is executed asynchronously.
I've tried 3 different versions of the pause function, it doesn't make any difference.
You can see this in the sandbox I put the code in.
(you must go to preferences - sandbox.config.json and turn of "Infinite loop protection" for it to work)
- Why isn't the code running synchronously, first showing the "start calculation..." message, and then the second message after a 3 second delay?
- Is there a better way to simulate running a time-expensive synchronous function?