Is it possible to sleep inside a Future in Scala.js ?
Something like:
Future {
Thread.sleep(1000)
println("ready")
}
If I try this then I get an exception saying that sleep
method does not exist.
It seems like that it is possible to sleep in JS : What is the JavaScript version of sleep()? even though it is not possible to block.
You cannot really pause in the middle of the future body, but you can register your future as a followup to a "delay" Future, which you can define as:
def delay(milliseconds: Int): Future[Unit] = {
val p = Promise[Unit]()
js.timers.setTimeout(milliseconds) {
p.success(())
}
p.future
}
and which you can then use as:
val readyLater = for {
delayed <- delay(1000)
} yield {
println("ready")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With