Timeout with withTimeout in Kotlin - Time & Space Complexity
When using withTimeout in Kotlin, we want to understand how the program's running time changes as the input or task size grows.
We ask: How does the timeout affect the total work done before stopping?
Analyze the time complexity of the following code snippet.
import kotlinx.coroutines.*
suspend fun doWorkWithTimeout(time: Long) {
withTimeout(time) {
repeat(1000) { i ->
delay(10) // simulate work
println("Working on task $i")
}
}
}
This code tries to do 1000 small tasks, each taking 10ms, but stops if the total time exceeds the given timeout.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
repeat(1000)loop that runs tasks. - How many times: Up to 1000 times, but may stop earlier if timeout occurs.
The number of tasks attempted depends on the timeout value. If the timeout is large, more tasks run; if small, fewer tasks run.
| Timeout (ms) | Approx. Tasks Completed |
|---|---|
| 100 | About 10 tasks |
| 5000 | About 500 tasks |
| 15000 | All 1000 tasks |
Pattern observation: The work done grows roughly linearly with the timeout until the maximum tasks are done.
Time Complexity: O(min(n, t/d))
This means the work grows with the smaller of the number of tasks n or the time limit t divided by the delay per task d.
[X] Wrong: "The loop always runs all 1000 tasks regardless of timeout."
[OK] Correct: The withTimeout stops the loop early if the time limit is reached, so fewer tasks may run.
Understanding how timeouts affect loops helps you reason about real-world programs that must stop work early to stay responsive or save resources.
What if we replaced delay(10) with a longer or shorter delay? How would the time complexity change?