-3

I have the below code with a busy waiting method wrapped in SetTimeout. In my opinion it should run in asynchronously because of the SetTimeout. However, it takes 20 seconds to complete. Can you explain why?

function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

function GetResultat() {
    sleep(5000);
    return Math.floor(Math.random()*11);
}
function HentTal() {
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            let resultat = GetResultat();
            if (resultat== 10) {
                throw new Error("Det fejlede big time");
            }
            if (resultat <= 7) {
                resolve(resultat);
            } else {
                reject();
            }
        }
        ,0)
    });
}

function resolved(value) {
    console.log(value);
}
function rejected() {
    console.log("No good");
}
Promise.all([HentTal(), HentTal(), HentTal(), HentTal()]).then(resolved).catch(rejected);
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • 2
    There are no asynchronous operations in the code to be run parallel. Everything is synchronous/blocking. – David Oct 03 '22 at 20:20
  • `Promise.all()` doesn't run the promises. It just waits for all of them to complete. – Barmar Oct 03 '22 at 20:20
  • 2
    They don't run in parallel. They run concurrently: They take turns sharing the thread. But if you aren't a good neighbor and hog the thread, then others don't get a chance to share. – Raymond Chen Oct 03 '22 at 20:22
  • 1
    JavaScript is single-threaded (unless you use WebWorkers) without preemption, so it can't run multiple functions concurrently. – Barmar Oct 03 '22 at 20:22
  • Thanks for your comments SetTimeout should run it asynchronously, like fetch, XMLHttpRequest, SetInterval. But maybe it is the highjacking of the thread that causes it. – Klaus Bøgestrand Oct 03 '22 at 20:29
  • 1
    @KlausBøgestrand Indeed. This is why you should _never_ use a "sleep" method like you did. It completely block the thread and freeze the web page. (And it wastes resources for no good reason.) – Ivar Oct 03 '22 at 20:43

2 Answers2

0

Seems like you thought, all the operations would run simultaneously, meaning on multiple threads at the same time. Javascript is not like that, it is single threaded, but heavily asynchronous. Your code just waited for all of the operations to complete, it didn't run them on multiple threads, it couldn't...

Bruno Pfohl
  • 451
  • 1
  • 8
0

Javascript is single thread... it means that you cannot run two processes in the CPU at the same time. Your sleep functions are executed inside an async execution. But once it starts executing, it blocks the single thread for 5 seconds. The other 3 sleeps keep waiting in the queue for the chance to take the CPU single thread.

Jose Marin
  • 802
  • 1
  • 4
  • 15