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
b should have been called sooner, but it waited until the function a completed.
No. b should be called after your synchronous code has executed because that's when a function passed to setTimeout is called.
Callback function of setTimeout is scheduled to run after the delay you specify as a second argument to setTimeout. This delay is the minimum amount of time it will take to run the callback function scheduled using setTimeout.
Once the timer expires, that callback function is put in a task queue and from there it is pushed to the call stack BUT it is only pushed once the call stack is empty.
In your case, call stack will be empty when your script has finished its execution.
I know js uses only one thread, but the processor could have switched between executing a and b during a's execution
That's not possible with only 1 thread. In Javascript, only one thing executes at a given time, unless you use another thread.
Does the processor always execute only one function at a time (if there is no await inside)
Yes. Even with await, function is paused until the promise is settled. Once the promise settles, that function continues execution and at that time, nothing else executes.
notice how x becomes NaN, since b is executed during a
No, there is no interference here. Function a is executed synchronously until the following statement
await sleep(1000);
While the function a is paused, waiting for the promise returned by sleep(...) to settle, during this time, function b is executed because its timer has expired and the call stack is empty.
Since both functions assign to same variable x, value of x is NaN because its value before function a resumes is undefined and performing addition on undefined leads to NaN.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With