0
0
Kotlinprogramming~5 mins

Timeout with withTimeout in Kotlin

Choose your learning style9 modes available
Introduction

Sometimes, you want to stop a task if it takes too long. withTimeout helps you do that easily.

You want to cancel a slow network request after 5 seconds.
You want to stop a long calculation if it exceeds a time limit.
You want to avoid freezing your app by limiting how long a task runs.
You want to retry a task only if it finishes quickly.
You want to make sure a background job does not run forever.
Syntax
Kotlin
withTimeout(timeMillis) {
    // code block to run with timeout
}

timeMillis is the maximum time in milliseconds to wait.

If the block takes longer, it throws TimeoutCancellationException.

Examples
Runs the code block and cancels if it takes more than 1 second.
Kotlin
withTimeout(1000) {
    println("This runs within 1 second")
}
Shows how to catch the timeout exception when the block takes too long.
Kotlin
try {
    withTimeout(500) {
        delay(1000)
    }
} catch (e: TimeoutCancellationException) {
    println("Timeout happened!")
}
Sample Program

This program tries to do 5 tasks, each taking 300ms. The total time is 1500ms, but the timeout is 1000ms, so it stops early and prints a timeout message.

Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    try {
        withTimeout(1000) {
            repeat(5) { i ->
                println("Working on task $i...")
                delay(300) // simulate work
            }
        }
    } catch (e: TimeoutCancellationException) {
        println("Task timed out!")
    }
}
OutputSuccess
Important Notes

Use withTimeout inside a coroutine or suspend function.

The timeout exception can be caught to handle the timeout gracefully.

Use withTimeoutOrNull if you want to get null instead of an exception on timeout.

Summary

withTimeout stops a block if it runs too long.

It throws an exception you can catch to handle timeouts.

Great for keeping your app responsive and avoiding long waits.