-
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
.bar
returns asetTimeout
function. - The callback we passed to
setTimeout
gets added to the Web API, thesetTimeout
function and bar get popped off the callstack. - The timer runs, in the meantime
foo
gets invoked and logs First. foo returns (undefined),baz
gets invoked, and the callback gets added to the queue. -
baz
logsThird
. The event loop sees the callstack is empty afterbaz
returned, after which the callback gets added to the call stack. - The callback logs
Second
.