0
0
KotlinHow-ToBeginner · 3 min read

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 a Long.

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 delay outside a coroutine or suspend function causes a compile error.
  • Using Thread.sleep() instead of delay blocks the thread and defeats coroutine benefits.
  • Not importing kotlinx.coroutines.delay can 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: delay suspends 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.