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
