Before we begin, I am a complete beginner in JS. I have been trying to run heavy tasks off the main thread so that the program doesn't have to hang for it to be done. Here is the following code ive written.
const tick = Date.now();
const log = (v) => console.log(`${v} \n Elapsed: ${Date.now() - tick}ms`);
const xd = () => {
return Promise.resolve().then(v => {
let i = 0;
while (i < 1000000000) {
i++;
}
return 'done';
})
};
log(' Synchronous 1');
xd().then(log);
log(' Synchronous 2');
let x = 0;
while (x < 1000000000) {
x++;
}
log(' Synchronous 3');
I expect the xd() to run async off the main thread and move on to the next lines of code and only to console.log when ready. In the meantime I want to run the same while loop code on the main thread. I tested out one of these while loops individuals and it takes around 550ms to compile on my computer. Theoretically I would expect both loops to finish at 550ms since they are the same thing however It ends up taking 1130ms, exactly double. Why isnt xd() function running in the background? Here is the output to this code.
Synchronous 1
Elapsed: 0ms
Synchronous 2
Elapsed: 4ms
Synchronous 3
Elapsed: 559ms
done
Elapsed: 1130ms
Process finished with exit code 0