JavaScript : Microtasks vs regular event loop task 😲

Natarajan Santhosh
2 min readJul 2, 2023

--

Sure! Here are some more examples to illustrate the behavior of microtasks:

Example 1: Chained Promises

```javascript

console.log(“Start”);

Promise.resolve()

. .then(() => console.log(“Step 1"))

. .then(() => console.log(“Step 2"))

. .then(() => console.log(“Step 3"));

console.log(“End”);

```

Output:

```

Start

End

Step 1

Step 2

Step 3

```

In this example, the chained promises are executed as microtasks, so their callbacks are placed in the microtask queue. They are processed before moving to the next task in the callback queue, resulting in the output order “Step 1,” “Step 2,” and “Step 3.”

Example 2: Mixing Microtasks and Regular Tasks

```javascript

console.log(“Start”);

Promise.resolve().then(() => console.log(“Microtask 1"));

setTimeout(() => console.log(“Timeout 1"), 0);

setTimeout(() => console.log(“Timeout 2"), 0);

Promise.resolve().then(() => console.log(“Microtask 2"));

console.log(“End”);

```

Output (The order might vary):

```

Start

End

Microtask 1

Microtask 2

Timeout 1

Timeout 2

```

In this example, we have a mix of microtasks and regular tasks. Both `Promise.resolve()` and `setTimeout` with a delay of 0 are executed asynchronously. However, microtasks are prioritized over regular tasks, so the microtasks (“Microtask 1" and “Microtask 2") are processed before the regular tasks (“Timeout 1" and “Timeout 2").

Example 3: Asynchronous Functions and await

```javascript

console.log(“Start”);

async function doAsync() {

. console.log(“Async Step 1");

. await Promise.resolve();

. console.log(“Async Step 2");

}

doAsync().then(() => console.log(“Async Step 3"));

console.log(“End”);

```

Output:

```

Start

Async Step 1

End

Async Step 2

Async Step 3

```

In this example, the `doAsync` function contains an `await` statement, which causes it to pause execution and schedule the next steps as microtasks. The output shows that “Async Step 1" is executed before “End,” and “Async Step 2" is executed before “Async Step 3.”

These examples demonstrate the importance of understanding microtasks and how they interact with the event loop to handle asynchronous code efficiently and in the expected order.

--

--

No responses yet