liveBook · Manning

Delay()

As explained in Kotlin in Action, 2E

delay is a coroutine-suspending function that pauses a coroutine for a specified duration without blocking its underlying thread.

delay() pauses a coroutine for a specified duration at a suspension point, allowing other coroutines to use the underlying thread instead of blocking it. section 14.6.2

Suspend one coroutine while another runs

fun main() = runBlocking { launch { log("second coroutine starts") delay(100.milliseconds) log("second coroutine resumes") } launch { log("third coroutine runs meanwhile") } } The first coroutine reaches delay(), suspends, and frees the thread. The third coroutine runs during the 100-millisecond pause; the suspended coroutine then resumes. section 14.6.2

Use delay() inside a suspending context such as runBlocking or a launched coroutine. Compiler-generated state preserves execution information so the coroutine can resume later. section 14.6.1 section 14.6.2

fun main() = runBlocking {
   log("The first, parent, coroutine starts")
   launch {
       log("The second coroutine starts and is ready to be suspended")
       delay(100.milliseconds)
       log("The second coroutine is resumed")
   }
   launch {
       log("The third coroutine can run in the meantime")
   }
   log("The first coroutine has launched two more coroutines")
}

Trace timestamps and coroutine names to observe suspension, concurrent progress, and resumption. section 14.6.2

How Kotlin in Action, 2E covers it

How deep it goes
Explains suspension points, interleaved execution, and compiler-managed resumption, but defers multithreaded dispatchers.
Examples
Demonstrates 100-millisecond suspension with launch, logging, timestamps, and a 500-millisecond runBlocking example.
What it assumes
Assumes coroutine builders such as runBlocking and launch, while introducing suspension points through delay().
What you can do after
Apply it via Kotlin coroutines to pause coroutine work without blocking the executing thread.
How it connects
Connects delay() with coroutines, launch, runBlocking, suspension points, and dispatchers.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.