0
0
Javascriptprogramming~5 mins

Await keyword behavior in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Await keyword behavior
O(n)
Understanding Time Complexity

When using the await keyword, we want to understand how waiting for asynchronous tasks affects the total time a program takes.

We ask: How does the program's running time grow as we add more awaited tasks?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


async function processTasks(tasks) {
  for (const task of tasks) {
    await task();
  }
}
    

This code runs a list of asynchronous tasks one after another, waiting for each to finish before starting the next.

Identify Repeating Operations
  • Primary operation: Looping through each task and awaiting its completion.
  • How many times: Once for each task in the input list.
How Execution Grows With Input

Each task waits fully before the next starts, so total time adds up.

Input Size (n)Approx. Operations
10Wait for 10 tasks one by one
100Wait for 100 tasks one by one
1000Wait for 1000 tasks one by one

Pattern observation: Total wait time grows directly with the number of tasks.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows in a straight line as you add more awaited tasks.

Common Mistake

[X] Wrong: "Using await inside a loop runs all tasks at the same time, so time stays the same no matter how many tasks."

[OK] Correct: Actually, await pauses the loop until the current task finishes, so tasks run one after another, making total time add up.

Interview Connect

Understanding how await affects timing helps you write efficient asynchronous code and explain your reasoning clearly in interviews.

Self-Check

What if we changed the loop to start all tasks without awaiting inside the loop, then awaited all at once? How would the time complexity change?