Ad space (banner)
๐ŸŽฏKotlin Lessons
Lesson 56 / 68

Waiting for a Fixed Amount of Time (Thread.sleep)

In this lesson you will learn how to pause for a set time with Thread.sleep in Kotlin, covering the basics of programs that deal with time. This is for anyone searching for "Kotlin Thread.sleep how to use".

Thread.sleep(milliseconds) pauses processing for the time you specify. Use it to space out calls to an API, or to slow a process down deliberately.

The sample code prints "Starting", waits one second with Thread.sleep(1000), and then prints "Ran after 1 second". Run it and you will feel the one-second gap between the two messages.

A common stumbling block for beginners is over-using Sleep and making the whole program feel unresponsive. Kotlin also has coroutines for concurrency, which are preferred for more flexible waiting.

In real-world development it is also used for waiting a moment before retrying, to avoid hammering a server with requests.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Kotlin directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)