0
0
Javascriptprogramming~5 mins

Async function syntax in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Async function syntax
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run an async function changes as the input grows.

How does waiting for asynchronous tasks affect the total time?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


async function fetchData(urls) {
  const results = [];
  for (const url of urls) {
    const response = await fetch(url);
    const data = await response.json();
    results.push(data);
  }
  return results;
}
    

This function fetches data from a list of URLs one by one, waiting for each to finish before starting the next.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Loop over each URL and wait for its fetch to complete.
  • How many times: Once for each URL in the input list.
How Execution Grows With Input

Each URL causes a fetch that takes some time. Since the function waits for each fetch before starting the next, the total time adds up.

Input Size (n)Approx. Operations
1010 fetches, done one after another
100100 fetches, each waited for in order
10001000 fetches, all waited for sequentially

Pattern observation: The total time grows roughly in direct proportion to the number of URLs.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows linearly with the number of URLs because each fetch waits for the previous one to finish.

Common Mistake

[X] Wrong: "Async functions always run all tasks at the same time, so time does not grow with input size."

[OK] Correct: In this code, each fetch waits for the previous one to finish, so tasks run one after another, making total time grow with input size.

Interview Connect

Understanding how async functions handle waiting helps you explain performance in real apps, showing you know how code runs over time.

Self-Check

What if we changed the code to start all fetches at once and then wait for all to finish? How would the time complexity change?