I'm a little confused on how setTimeOut works: why the callback function didn't got the values it needed when it was invoked, but got them from the bottom of the script?
I expected it to print 5 and not 7..
what am I missing ?
any help is appreciated, thanks!
let foo = () => {
console.log(x);
};
let x = 5;
setTimeout(foo, 0); //7
for (let i = 0; i < 10000000000; i ) {} //just to waste some time because the timeOut is actually 4ms
x = 7;
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Callback function of the setTimeout
isn't executed until the call stack is empty and the call stack won't be empty until the execution of your synchronous javascript code completes.
As the last statement overwrites the value of x
, when the callback function of setTimeout
is invoked, it logs the latest value, i.e. 7.
It seems that you are expecting the callback function of setTimeout
to be executed while the for
loop is executing BUT that's not how Javascript works.
Once the timer of the setTimeout
expires, callback function of the setTimeout
is enqueued in the task queue. From the task queue, event loop will push this callback on the call stack BUT the callback function won't be pushed on the call stack until no other javascript code is executing, i.e. the call stack is empty.
It doesn't matters how long it takes for the synchronous script execution to end; no scheduled callback will be executed until the synchronous script execution ends.
Keep in mind that all your code executes on a single thread.
Also note that the number of milliseconds passed to setTimeout
is NOT the exact time after which the callback function will be executed; it's the minimum time after which the callback function will be invoked.