How to set delay in Kotlin?

Issue

I just want to wait 2 or 3 seconds, I know how to do it in Java and I tried it, but no idea about kotlin

something simple like:

println("hello")
// a 2 seconds delay
println("world")

Solution

there are some ways:

1- use Handler(base on mili-second)(Deprecated):

println("hello")
Handler().postDelayed({
   println("world")
}, 2000)

2- by using Executors(base on second):

println("hello")
Executors.newSingleThreadScheduledExecutor().schedule({
    println("world")
}, 2, TimeUnit.SECONDS)

3- by using Timer(base on mili-second):

println("hello")
Timer().schedule(2000) {
  println("world")
}

Answered By – soheil ghanbari

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published