Bird
Raised Fist0
Kotlinprogramming~20 mins

Timeout with withTimeout in Kotlin - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Timeout Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Kotlin code using withTimeout?
Consider the following Kotlin code snippet using withTimeout. What will be printed when this code runs?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    try {
        withTimeout(1000L) {
            repeat(5) { i ->
                println("Processing $i")
                delay(400L)
            }
        }
    } catch (e: TimeoutCancellationException) {
        println("Timeout occurred")
    }
}
A
Processing 0
Processing 1
Processing 2
Timeout occurred
B
Processing 0
Processing 1
Processing 2
Processing 3
Processing 4
CTimeout occurred
D
Processing 0
Timeout occurred
Attempts:
2 left
💡 Hint
Think about how long each delay takes and the total timeout limit.
❓ Predict Output
intermediate
2:00remaining
What happens if delay exceeds withTimeout duration?
What will be the output of this Kotlin code snippet?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    try {
        withTimeout(500L) {
            delay(1000L)
            println("Finished")
        }
    } catch (e: TimeoutCancellationException) {
        println("Timeout!")
    }
}
ATimeout!
BFinished
CNo output
DRuntimeException
Attempts:
2 left
💡 Hint
The delay is longer than the timeout duration.
🔧 Debug
advanced
2:00remaining
Identify the error in this withTimeout usage
This Kotlin code snippet is intended to timeout after 1 second, but it does not behave as expected. What is the error?
Kotlin
import kotlinx.coroutines.*

fun main() = runBlocking {
    withTimeout(1000L) {
        repeat(3) { i ->
            println("Step $i")
            Thread.sleep(500L)
        }
    }
    println("Done")
}
AwithTimeout requires delay, not Thread.sleep, otherwise it throws an exception.
BUsing Thread.sleep blocks the thread and prevents cancellation, so timeout does not work.
CThe timeout value is too short to complete the loop, causing an immediate cancellation.
DrunBlocking cannot be used with withTimeout.
Attempts:
2 left
💡 Hint
Consider how blocking calls affect coroutine cancellation.
📝 Syntax
advanced
2:00remaining
Which option correctly uses withTimeout to return a value?
Select the Kotlin code snippet that correctly uses withTimeout to return a value from a suspending block.
A
val result = withTimeout(1000L) {
    delay(500L)
    println("Success")
}
println(result)
B
val result = withTimeout(1000L) {
    delay(500L)
    return "Success"
}
println(result)
C
val result = withTimeout(1000L) {
    delay(500L)
    "Success"
}
println(result)
D
val result = withTimeout(1000L) {
    delay(500L)
    "Success"
}
return result
println(result)
Attempts:
2 left
💡 Hint
Remember how to return values from lambda blocks in Kotlin.
🚀 Application
expert
3:00remaining
How to handle multiple withTimeout calls with different durations?
You want to run two suspending tasks sequentially with different timeouts: first task with 1 second timeout, second with 2 seconds timeout. Which Kotlin code snippet correctly implements this?
A
runBlocking {
    val first = withTimeout(1000L) {
        delay(900L)
        "First"
    }
    val second = withTimeout(2000L) {
        delay(1500L)
        "Second"
    }
    println("$first and $second")
}
B
runBlocking {
    withTimeout(3000L) {
        val first = delay(900L)
        val second = delay(1500L)
        println("First and Second")
    }
}
C
runBlocking {
    val first = withTimeout(1000L) {
        delay(1100L)
        "First"
    }
    val second = withTimeout(2000L) {
        delay(1500L)
        "Second"
    }
    println("$first and $second")
}
D
runBlocking {
    val first = withTimeoutOrNull(1000L) {
        delay(1100L)
        "First"
    } ?: "Timeout"
    val second = withTimeoutOrNull(2000L) {
        delay(1500L)
        "Second"
    } ?: "Timeout"
    println("$first and $second")
}
Attempts:
2 left
💡 Hint
Consider how to handle tasks that might timeout without throwing exceptions.

Practice

(1/5)
1. What does the Kotlin function withTimeout do?
easy
A. It cancels all running coroutines immediately.
B. It repeats a block of code until a timeout occurs.
C. It stops a block of code if it runs longer than the specified time.
D. It delays the execution of a block for a fixed time.

Solution

  1. Step 1: Understand the purpose of withTimeout

    withTimeout is designed to stop a block of code if it exceeds a given time limit.
  2. Step 2: Compare options with the definition

    Only "It stops a block of code if it runs longer than the specified time." correctly describes this behavior. Other options describe different coroutine behaviors.
  3. Final Answer:

    It stops a block of code if it runs longer than the specified time. -> Option C
  4. Quick Check:

    withTimeout stops code after time limit [OK]
Hint: Remember: withTimeout interrupts long-running code [OK]
Common Mistakes:
  • Confusing withTimeout with delay function
  • Thinking it repeats code instead of stopping
  • Assuming it cancels all coroutines globally
2. Which of the following is the correct syntax to use withTimeout in Kotlin?
easy
A. withTimeout(1000) { /* code block */ }
B. withTimeout { 1000, /* code block */ }
C. withTimeout[1000] { /* code block */ }
D. withTimeout: 1000 { /* code block */ }

Solution

  1. Step 1: Recall the function signature

    The correct syntax uses parentheses with the timeout in milliseconds as the first argument, followed by a lambda block.
  2. Step 2: Match options with correct syntax

    withTimeout(1000) { /* code block */ } matches this pattern exactly. Others use incorrect brackets or misplaced arguments.
  3. Final Answer:

    withTimeout(1000) { /* code block */ } -> Option A
  4. Quick Check:

    withTimeout uses parentheses for timeout [OK]
Hint: Use parentheses with timeout value before code block [OK]
Common Mistakes:
  • Using square brackets instead of parentheses
  • Placing timeout inside the block instead of argument
  • Using colon instead of parentheses
3. What will be the output of this Kotlin code?
import kotlinx.coroutines.*

fun main() = runBlocking {
    try {
        withTimeout(100) {
            repeat(5) { i ->
                println("Processing $i")
                delay(50)
            }
        }
    } catch (e: TimeoutCancellationException) {
        println("Timeout occurred")
    }
}
medium
A. Processing 0 Processing 1 Processing 2 Processing 3 Processing 4
B. Processing 0 Processing 1 Timeout occurred
C. Timeout occurred
D. Processing 0 Timeout occurred Processing 1

Solution

  1. Step 1: Analyze the timing of the loop and timeout

    Each iteration delays 50ms. After two iterations, 100ms timeout is reached.
  2. Step 2: Determine output before timeout

    "Processing 0" and "Processing 1" print before timeout triggers. Then exception is caught and "Timeout occurred" prints.
  3. Final Answer:

    Processing 0 Processing 1 Timeout occurred -> Option B
  4. Quick Check:

    Timeout stops after 2 prints + exception message [OK]
Hint: Multiply delay by iterations to compare with timeout [OK]
Common Mistakes:
  • Assuming all iterations print before timeout
  • Ignoring exception catch block
  • Thinking timeout cancels immediately without partial output
4. Identify the error in this Kotlin code using withTimeout:
import kotlinx.coroutines.*

fun main() = runBlocking {
    withTimeout(100) {
        delay(200)
        println("Done")
    }
}
medium
A. TimeoutCancellationException is thrown because delay exceeds timeout.
B. Syntax error: withTimeout requires a try-catch block.
C. No error; code runs and prints "Done" after 200ms.
D. Delay function cannot be used inside withTimeout.

Solution

  1. Step 1: Understand withTimeout behavior with delay

    The delay of 200ms exceeds the 100ms timeout, causing a TimeoutCancellationException.
  2. Step 2: Check error handling

    No try-catch is present, so exception will be thrown and program will crash.
  3. Final Answer:

    TimeoutCancellationException is thrown because delay exceeds timeout. -> Option A
  4. Quick Check:

    Delay longer than timeout causes exception [OK]
Hint: Delay longer than timeout causes exception unless caught [OK]
Common Mistakes:
  • Assuming code waits full delay then prints
  • Thinking try-catch is mandatory syntax
  • Believing delay can't be used inside withTimeout
5. You want to run a network request that should timeout after 500ms. Which Kotlin code correctly uses withTimeout to achieve this and handle timeout gracefully?
hard
A. try { networkRequest() withTimeout(500) } catch (e: TimeoutCancellationException) { println("Request timed out") }
B. withTimeout(500) { try { networkRequest() } catch (e: TimeoutCancellationException) { println("Request timed out") } }
C. withTimeoutOrNull(500) { networkRequest() } ?: println("Request timed out")
D. try { withTimeout(500) { networkRequest() } } catch (e: TimeoutCancellationException) { println("Request timed out") }

Solution

  1. Step 1: Understand correct placement of withTimeout and try-catch

    The timeout should wrap the networkRequest call, and the exception should be caught outside to handle timeout.
  2. Step 2: Evaluate options for proper structure

    try { withTimeout(500) { networkRequest() } } catch (e: TimeoutCancellationException) { println("Request timed out") } correctly wraps networkRequest inside withTimeout and catches the exception outside. withTimeout(500) { try { networkRequest() } catch (e: TimeoutCancellationException) { println("Request timed out") } } catches inside, which won't catch timeout. withTimeoutOrNull(500) { networkRequest() } ?: println("Request timed out") uses withTimeoutOrNull (valid but different). try { networkRequest() withTimeout(500) } catch (e: TimeoutCancellationException) { println("Request timed out") } misplaces withTimeout after networkRequest.
  3. Final Answer:

    try { withTimeout(500) { networkRequest() } } catch (e: TimeoutCancellationException) { println("Request timed out") } -> Option D
  4. Quick Check:

    Wrap withTimeout around call, catch outside [OK]
Hint: Wrap withTimeout around call, catch exception outside [OK]
Common Mistakes:
  • Catching exception inside withTimeout block
  • Placing withTimeout after the call
  • Confusing withTimeout with withTimeoutOrNull
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard