This article explores different ways to sleep in Kotlin.

1. Using Thread.sleep() function

To set the current thread to sleep, we can use the Thread.sleep() function. It takes in the total number of milliseconds to sleep, and can be used as follows:

Download Code

Output:

Stopping…
Resuming…

2. Using TimeUnit

Alternatively, we can use the sleep() function of TimeUnit which automatically converts the specified time unit into the form required by the Thread.sleep() function. To sleep in seconds, use TimeUnit.SECONDS.

Download Code

Output:

Stopping…
Resuming…

 
Similarly, to sleep in milliseconds, use TimeUnit.MILLISECONDS. The TimeUnit offers a total of 7 Time units i.e, NANOSECONDS, MICROSECONDS, MILLISECONDS, SECONDS, MINUTES, HOURS, and DAYS.

Download Code

Output:

Stopping…
Resuming…

That’s all about sleeping in Kotlin.