let x = 0;
function a() {
console.log("called a()");
for (let i=0; i<123456789; ++i) {
x += Math.sqrt(2);
}
console.log("x = "+x);
}
function b() {
x = undefined;
console.log("called b()");
}
setTimeout(b, 20);
a();
output:
called a()
x = 174594265.7306214
called b()
b should have been called sooner, but it waited until the function a completed.
I know js uses only one thread, but the processor could have switched between executing a and b during a's execution. Does the processor always execute only one function at a time (if there is no await inside)? In nodejs and in website javascript?
EDIT:
Here is an await example:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
let x = 0;
async function a() {
console.log("called a()");
await sleep(1000);
for (let i=0; i<123456789; ++i) {
x += Math.sqrt(2);
}
console.log("x = "+x);
}
function b() {
x = undefined;
console.log("called b()");
}
setTimeout(b, 20);
a();
output:
called a()
called b()
x = NaN
notice how x becomes NaN, since b is executed during a