JS Titbits | Sync vs Async
King Elisha

King Elisha @elishaking

Location:
Abuja, Nigeira
Joined:
Nov 19, 2019

JS Titbits | Sync vs Async

Publish Date: Jul 7 '20
1 0

In Javascript, all synchronous code in a given script is executed before any asynchronous code.

For example, take a look at the code below

setTimeout(() => {
  console.log("async");
}, 0);

for (let i = 0; i < 5; i++) {
  console.log("sync...", i);
}
Enter fullscreen mode Exit fullscreen mode

The result of running the above block of code is

sync... 0
sync... 1
sync... 2
sync... 3
sync... 4
async
Enter fullscreen mode Exit fullscreen mode

The delay on the setTimeout function is set to 0, but the handler function is executed last after all synchronous code has been executed.

Comments 0 total

    Add comment