How to Use Delay in Coroutine in Kotlin: Simple Guide
In Kotlin, you use
delay(timeMillis: Long) inside a coroutine to pause its execution without blocking the thread. This function suspends the coroutine for the specified milliseconds, allowing other coroutines to run during the wait.Syntax
The delay function is a suspend function that takes one parameter:
timeMillis: The time to wait in milliseconds as aLong.
You must call delay from within a coroutine or another suspend function.
kotlin
suspend fun example() {
kotlinx.coroutines.delay(timeMillis = 1000L) // pauses coroutine for 1 second
}Example
This example shows how to use delay inside a coroutine launched with runBlocking. It prints messages before and after a 1-second pause.
kotlin
import kotlinx.coroutines.* fun main() = runBlocking { println("Start") delay(1000L) // pause for 1 second println("End after delay") }
Output
Start
End after delay
Common Pitfalls
Common mistakes when using delay include:
- Calling
delayoutside a coroutine or suspend function causes a compile error. - Using
Thread.sleep()instead ofdelayblocks the thread and defeats coroutine benefits. - Not importing
kotlinx.coroutines.delaycan cause confusion with other delay functions.
kotlin
import kotlinx.coroutines.* fun main() { // Wrong: delay called outside coroutine // delay(1000L) // ERROR // Correct way: runBlocking { delay(1000L) // works fine } // Wrong: Thread.sleep blocks thread Thread.sleep(1000L) // blocks main thread }
Quick Reference
Remember these tips when using delay:
- Use inside coroutines only.
- Non-blocking pause:
delaysuspends coroutine without blocking thread. - Parameter: time in milliseconds as
Long. - Do not use
Thread.sleep()in coroutines.
Key Takeaways
Use delay inside coroutines or suspend functions to pause without blocking threads.
delay takes time in milliseconds as a Long and suspends the coroutine for that duration.
Never use Thread.sleep() in coroutines because it blocks the thread.
delay allows other coroutines to run while waiting, improving efficiency.
Always import kotlinx.coroutines.delay to avoid confusion with other delay functions.