𝗦𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝘃𝘀 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁
JavaScript runs on a single thread. This means it handles one task at a time. You must understand how it manages different types of tasks to build fast web apps.
Synchronous JavaScript
In synchronous code, tasks run in a specific order. Each line waits for the previous line to finish.
- Code executes line by line.
- Each task blocks the next task.
- The flow is predictable but slow if a task takes a long time.
Asynchronous JavaScript
Asynchronous code allows tasks to run in the background. It does not stop your main program from running. This makes your apps feel fast and responsive.
How it works:
- Call Stack: This tracks your current functions.
- Web APIs: The browser handles heavy tasks like timers or data fetching here.
- Callback Queue: Once a background task finishes, it waits here.
- Event Loop: This moves tasks from the queue to the stack when the stack is empty.
Process vs Thread
To understand execution, you should know the difference between processes and threads.
Process
A process is an independent program.
- It has its own memory.
- It uses a unique Process ID.
- It is managed by the operating system.
Thread
A thread is a small unit of execution inside a process.
- Threads share memory with other threads in the same process.
- They allow a single program to do many things at once.
- This makes communication faster between tasks.
Summary
Use synchronous code for simple, quick steps. Use asynchronous code for tasks that take time, like fetching data. This prevents your website from freezing.
Source: https://dev.to/vidhya_murali_5aabe7784bd/synchronous-and-asynchronous-in-javascript-14ip