Await keyword behavior in Javascript - Time & Space 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?
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.
- Primary operation: Looping through each task and awaiting its completion.
- How many times: Once for each task in the input list.
Each task waits fully before the next starts, so total time adds up.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Wait for 10 tasks one by one |
| 100 | Wait for 100 tasks one by one |
| 1000 | Wait for 1000 tasks one by one |
Pattern observation: Total wait time grows directly with the number of tasks.
Time Complexity: O(n)
This means the total time grows in a straight line as you add more awaited tasks.
[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.
Understanding how await affects timing helps you write efficient asynchronous code and explain your reasoning clearly in interviews.
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?