Skip to content

JavaScript Event loop

Beijukabruno edited this page Sep 21, 2022 · 1 revision

setTimeout() JavaScript Event loop function .

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.

Example using setTimeout()

const foo = () => console.log("First");

const bar = () => setTimeout(() => console.log("Second"), 500);

const baz = () => console.log("Third");

bar();

foo();

baz();

How it works

  • We invoke bar. bar returns a setTimeout function.
  • The callback we passed to setTimeout gets added to the Web API, the setTimeout 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 logs Third. The event loop sees the callstack is empty after baz returned, after which the callback gets added to the call stack.
  • The callback logs Second.
Clone this wiki locally