0

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

Rohan G
  • 51
  • 2
  • 9
  • javascript is single threaded... so my guess is that the while-loop in your promise is blocking the thread. if you'd replace the while loops with a settimeout of 550ms you should get your expected behaviour... it's a good example why js is not good for heavy computations – Argee May 05 '20 at 13:15
  • [The `then` block is triggered immediately on a resolved promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then), which justifies the behavior presented here. – E_net4 May 05 '20 at 13:22
  • Asynchronous means parallel wait, not parallel code execution. A for loop is code execution so cannot happen in parallel with other things. But waiting for data from disk or waiting for packets from the network or waiting for a mouse click involves no code execution so javascript waits for all of them in parallel (but can only execute code one at a time) – slebetman May 05 '20 at 13:55

0 Answers0