0Pricing
Kotlin Academy · Lesson

withTimeout and withTimeoutOrNull

Limit execution time with timeout wrappers and handle TimeoutCancellationException.

withTimeout and withTimeoutOrNull is a free Kotlin Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Kotlin Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Timeouts?

Coroutines can hang indefinitely on network or I/O. withTimeout cancels the block if it does not complete within the given milliseconds.

import kotlinx.coroutines.*
fun main() = runBlocking {
    try {
        withTimeout(200) {
            delay(1000)  // simulates slow network
            println("This never prints")
        }
    } catch (e: TimeoutCancellationException) {
        println("Timed out!")
    }
}

withTimeout Basics

withTimeout(millis) { ... } throws TimeoutCancellationException (a subclass of CancellationException) if the block exceeds the limit.

import kotlinx.coroutines.*
suspend fun fetchData(): String {
    delay(100)
    return "data"
}
fun main() = runBlocking {
    val result = withTimeout(500) {
        fetchData()
    }
    println(result) // data
}

withTimeoutOrNull

withTimeoutOrNull returns null on timeout instead of throwing, making it easier to handle timeouts as normal flow.

import kotlinx.coroutines.*
fun main() = runBlocking {
    val result: String? = withTimeoutOrNull(200) {
        delay(1000)
        "done"
    }
    println(result ?: "Timeout — using default")
}

Timeout with Return Value

Both functions return the value of the last expression in the block on success.

import kotlinx.coroutines.*
fun main() = runBlocking {
    val response = withTimeoutOrNull(500) {
        delay(100)
        mapOf("status" to 200, "body" to "OK")
    }
    println(response?.get("status")) // 200
}

Nesting Timeouts

Inner timeouts expire first. The outer timeout only fires if the inner one does not cancel first — useful for per-request vs global timeouts.

import kotlinx.coroutines.*
fun main() = runBlocking {
    withTimeoutOrNull(1000) {       // global
        withTimeoutOrNull(200) {    // per-call
            delay(300)
            println("inner done")  // won't print
        } ?: println("Inner timed out")
        delay(100)
        println("outer still running")
    }
}

TimeoutCancellationException

TimeoutCancellationException is a CancellationException, so it is treated as normal cancellation by the coroutine machinery and does not propagate to the parent scope.

import kotlinx.coroutines.*
fun main() = runBlocking {
    val job = launch {
        try {
            withTimeout(100) { delay(1000) }
        } catch (e: TimeoutCancellationException) {
            println("Caught in child: ${e.message}")
        }
    }
    job.join()
    println("Parent still running: ${isActive}")
}

Resource Cleanup on Timeout

Use finally inside withTimeout to release resources even when time runs out.

import kotlinx.coroutines.*
fun main() = runBlocking {
    val result = withTimeoutOrNull(150) {
        try {
            println("Opening resource")
            delay(300)
            "result"
        } finally {
            println("Closing resource") // always runs
        }
    }
    println("Result: $result")
}

Retry with Timeout

Combine timeout with retry logic: attempt an operation with a per-attempt timeout, retry on null result.

import kotlinx.coroutines.*
suspend fun tryFetch(attempt: Int): String? = withTimeoutOrNull(200) {
    delay(if (attempt < 3) 300L else 100L) // fails first 2 attempts
    "success on attempt $attempt"
}
fun main() = runBlocking {
    var result: String? = null
    var attempt = 1
    while (result == null) {
        result = tryFetch(attempt++)
    }
    println(result)
}

withTimeout in ViewModel

In Android ViewModels, wrap repository calls with withTimeoutOrNull in viewModelScope.launch to show error state on slow responses.

import kotlinx.coroutines.*
// Pseudocode pattern:
suspend fun loadUser(): String = withTimeoutOrNull(3000) {
    // repo.getUser()
    delay(100)
    "Alice"
} ?: "Timeout — using cached data"
fun main() = runBlocking { println(loadUser()) }

Accuracy Caveat

withTimeout relies on the coroutine dispatcher. In tests using TestCoroutineScheduler, time is virtual and can be advanced manually.

import kotlinx.coroutines.*
// In unit tests with runTest:
// runTest {
//     withTimeout(1000) {
//         delay(999)  // virtual time — completes instantly
//         println("done")
//     }
// }
fun main() = runBlocking {
    println("Use runTest for virtual-time timeout testing")
}

Choosing Between the Two

Use withTimeout when timeout is an error. Use withTimeoutOrNull when timeout is an expected outcome (e.g., cache miss, optional prefetch).

import kotlinx.coroutines.*
fun main() = runBlocking {
    // Mandatory: throw on timeout
    // withTimeout(500) { criticalOp() }

    // Optional: null on timeout
    val cached = withTimeoutOrNull(50) {
        delay(200); "fresh"
    } ?: "stale"
    println(cached)
}

Quick Check

What does withTimeoutOrNull return when the block exceeds the time limit?

Recap

withTimeout throws on timeout; withTimeoutOrNull returns null. Both cancel the block cooperatively and run finally blocks. Use finally for resource cleanup and withTimeoutOrNull when timeout is an expected outcome.

Frequently asked questions

Is the “withTimeout and withTimeoutOrNull” lesson free?

Yes — the full text of “withTimeout and withTimeoutOrNull” is free to read here on the web, and the Kotlin Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Kotlin Academy course, upgrade to CoddyKit PRO.

What will I learn in “withTimeout and withTimeoutOrNull”?

Limit execution time with timeout wrappers and handle TimeoutCancellationException. You practise Kotlin Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Kotlin Academy?

No prior experience is required. Kotlin Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “withTimeout and withTimeoutOrNull” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Kotlin Academy lesson?

Yes. Every Kotlin Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Cooperative Cancellation: isActive and ensureActive
  2. withTimeout and withTimeoutOrNull
  3. Cleanup with finally and NonCancellable
  4. Cancellation Propagation in Coroutine Hierarchies
← Back to Kotlin Academy