Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sleep inside Future in Scala.js

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.

like image 644
jhegedus Avatar asked Oct 07 '17 07:10

jhegedus


1 Answers

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")
}
like image 154
sjrd Avatar answered Nov 11 '22 00:11

sjrd