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);
>Solution :
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.