-
Notifications
You must be signed in to change notification settings - Fork 11
JavaScript Event loop
Beijukabruno edited this page Sep 21, 2022
·
1 revision
setTimeout() method calls a function after a specified amount of time or we can say it lets us delaytasks without blocking the main thread. respond() function returns a setTimeout function provided to us by the Web API.
const foo = () => console.log("First");
const bar = () => setTimeout(() => console.log("Second"), 500);
const baz = () => console.log("Third");
bar();
foo();
baz();
- We invoke
bar.barreturns asetTimeoutfunction. - The callback we passed to
setTimeoutgets added to the Web API, thesetTimeoutfunction and bar get popped off the callstack. - The timer runs, in the meantime
foogets invoked and logs First. foo returns (undefined),bazgets invoked, and the callback gets added to the queue. -
bazlogsThird. The event loop sees the callstack is empty afterbazreturned, after which the callback gets added to the call stack. - The callback logs
Second.