0
0
Kotlinprogramming~30 mins

Timeout with withTimeout in Kotlin - Mini Project: Build & Apply

Choose your learning style9 modes available
Timeout with withTimeout
📖 Scenario: Imagine you are making a simple program that waits for a task to finish, but you don't want to wait forever. You want to stop waiting if it takes too long.
🎯 Goal: You will build a Kotlin program that uses withTimeout to stop waiting after a set time.
📋 What You'll Learn
Create a suspend function that simulates a long task
Set a timeout duration using withTimeout
Run the task inside withTimeout
Handle the timeout exception and print a message
💡 Why This Matters
🌍 Real World
Timeouts are useful when waiting for slow tasks like network calls or user input, so your program doesn't freeze or wait forever.
💼 Career
Many jobs require handling timeouts to keep apps responsive and avoid crashes, especially in mobile and backend development.
Progress0 / 4 steps
1
Create a suspend function to simulate a long task
Write a suspend function called longTask that waits for 3000 milliseconds using delay(3000).
Kotlin
Need a hint?

Use suspend fun to create a function that can pause. Use delay(3000) to wait 3 seconds.

2
Set a timeout duration using withTimeout
Create a val timeoutMillis and set it to 2000L to represent 2000 milliseconds timeout.
Kotlin
Need a hint?

Use val timeoutMillis = 2000L to set the timeout to 2 seconds.

3
Run the task inside withTimeout
Write a suspend function called runWithTimeout that uses withTimeout(timeoutMillis) to run longTask().
Kotlin
Need a hint?

Use withTimeout(timeoutMillis) { longTask() } inside the new suspend function.

4
Handle timeout exception and print result
Write a main function that calls runBlocking and inside it calls runWithTimeout(). Catch TimeoutCancellationException and print "Timeout happened!". If no timeout, print "Task completed".
Kotlin
Need a hint?

Use try { runWithTimeout() } and catch (e: TimeoutCancellationException) to print the timeout message.