๐—๐—ฎ๐˜ƒ๐—ฎ๐—ฆ๐—ฐ๐—ฟ๐—ถ๐—ฝ๐˜ ๐—ฆ๐˜†๐—ป๐—ฐ ๐˜ƒ๐˜€ ๐—”๐˜€๐˜†๐—ป๐—ฐ

JavaScript runs code one line at a time. This is synchronous behavior. The engine finishes one task before it starts the next.

JavaScript has one main thread. It does one task at a time.

Some tasks take time.

If JavaScript waits for these tasks, your page freezes. Buttons stop responding. The user experience suffers.

Asynchronous behavior solves this. JavaScript starts a long task. It continues running the rest of your code. It does not block the program.

Look at setTimeout.

  1. Log Hi.
  2. Set timer for 2 seconds.
  3. Log Bye.

The output is: Hi Bye Run after 2 seconds

JavaScript does not wait for the timer. It prints Bye first.

Even a 0 second timer runs after the main code. The browser handles these tasks. JavaScript gets a notification when the task ends.

Main points:

Source: https://dev.to/tejas_khanolkar_473f3ed1a/synchronous-and-asynchronous-behavior-of-javascript-2cp1