๐๐ฎ๐๐ฎ๐ฆ๐ฐ๐ฟ๐ถ๐ฝ๐ ๐ฆ๐๐ป๐ฐ ๐๐ ๐๐๐๐ป๐ฐ
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.
- Fetching data from a server.
- Waiting for a timer.
- Reading local storage.
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.
- Log Hi.
- Set timer for 2 seconds.
- 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:
- Synchronous: Code runs in order.
- Single-threaded: One task at a time.
- Asynchronous: Long tasks run in the background.
- Result: Your page stays responsive.
Source: https://dev.to/tejas_khanolkar_473f3ed1a/synchronous-and-asynchronous-behavior-of-javascript-2cp1