DEV Community

Priyaramu
Priyaramu

Posted on

Learn Synchronous and Asynchronous JavaScript

Synchronous

In synchronous programming, tasks are done one after another in order. Each line of code waits for the previous one to finish before moving to the next. This means the program runs step by step in a clear and predictable way.

console.log("Start");
console.log("Task 1");
console.log("Task 2");
console.log("End");
Enter fullscreen mode Exit fullscreen mode

In this example, "Start" is printed first, followed by "Task 1", then "Task 2", and finally "End". Each line runs only after the previous one has finished. This shows that the code executes in a fixed order, step by step, without skipping any task.

Asynchronous

In asynchronous programming, tasks can run independently without waiting for previous tasks to complete. While one task is in progress, other tasks can continue running. This improves performance and makes applications faster and smoother.

console.log("Start");

setTimeout(function() {
  console.log("Task 1");
}, 2000);

console.log("End");

Output:
Start
End
Task 1
Enter fullscreen mode Exit fullscreen mode

In this example, "Start" is printed first, followed by "End". The "Task 1" message is printed after a delay. This happens because the setTimeout function runs asynchronously, so the code does not wait and continues executing the next line.

How Asynchronous JavaScript Works

Call Stack:

The call stack is where JavaScript runs functions.
It follows a simple rule: one function runs at a time, in order.
Each function is added to the stack, executed, and then removed before the next one runs.

Web APIs (Browser)

Some tasks like setTimeout, API calls, and event listeners are handled by the browser using Web APIs.

When you use something like setTimeout, JavaScript sends it to the Web API.
The Web API handles the waiting time, so the main code does not stop.

Callback Queue

After the Web API finishes its task (like waiting for time), it sends the function (callback) to the callback queue.

Event Loop

The event loop keeps checking the call stack.

  • If the call stack is empty
  • It takes functions from the callback queue
  • And moves them to the call stack for execution

That’s why delayed tasks run after the main code finishes.

Top comments (0)