Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Kotlin Dictionary
  3. delay() / withTimeout()

delay() / withTimeout()

Kotlin coroutines' delay() suspends execution for a specified duration without blocking the thread. withTimeout() throws an exception if the block does not complete within the time limit.

Syntax

// delay — suspends the coroutine for the specified number of milliseconds
delay(milliseconds: Long)

// withTimeout — runs a block with a timeout (throws an exception if exceeded)
val result = withTimeout(milliseconds: Long) {
    // your code
    result
}

// withTimeoutOrNull — returns null instead of throwing on timeout
val result: Type? = withTimeoutOrNull(milliseconds: Long) {
    // your code
    result
}

Functions

FunctionDescription
delay(ms)Suspends the coroutine for the specified number of milliseconds without blocking the thread.
withTimeout(ms) { }Throws a TimeoutCancellationException if the block does not complete within the time limit.
withTimeoutOrNull(ms) { }Returns null on timeout instead of throwing an exception.

Sample Code

import kotlinx.coroutines.*

suspend fun slowOperation(): String {
    delay(500)  // Simulates an operation that takes 0.5 seconds
    return "Done"
}

fun main() = runBlocking {
    // Use delay to wait (unlike Thread.sleep, it does not block the thread).
    println("Start")
    delay(200)
    println("After 200ms")  // After 200ms

    // Use withTimeout to set a time limit.
    try {
        val result = withTimeout(1000) {
            slowOperation()  // Completes in 500ms (within the timeout)
        }
        println(result)  // Done
    } catch (e: TimeoutCancellationException) {
        println("Timed out!")
    }

    // withTimeoutOrNull returns null if the timeout is exceeded.
    val result1 = withTimeoutOrNull(1000) {
        slowOperation()  // 500ms (completes in time)
    }
    println(result1)  // Done

    val result2 = withTimeoutOrNull(300) {
        slowOperation()  // 500ms (times out)
    }
    println(result2)  // null

    // Branch on the null result to handle the timeout case.
    if (result2 == null) {
        println("Did not complete in time")  // Did not complete in time
    }
}

Notes

delay() only suspends the coroutine without occupying the thread, so other coroutines can run on the same thread. Use it instead of Thread.sleep().

For timeout handling, withTimeoutOrNull() is often more convenient than withTimeout() because you can check the return value instead of catching an exception.

See launch / async for launching coroutines, and Flow — Basics for asynchronous data streams.

If you find any errors or copyright issues, please .