5

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.

jhegedus
  • 18,516
  • 11
  • 84
  • 147
  • Just use `pausecomp` from the linked solution :) (I assume you are fully aware of why you would not want to do this most of the time). – gzm0 Oct 07 '17 at 08:09
  • I think the answer given below is perfectly fine and there is no reason why someone should not use that anytime they wish to delay a future. – jhegedus Oct 07 '17 at 12:20

1 Answers1

6

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")
}
sjrd
  • 20,350
  • 2
  • 57
  • 81
  • Depending on whether you actually want to sleep a specific amount of time or just want something to happen "later" (which is often needed for testing), note the notYet function in the jsExt library, which does a looser version of this: https://github.com/jducoeur/jsext – Justin du Coeur Oct 07 '17 at 15:16
  • Hm... I don't really get what you mean ... later ? who decides what is later ? later in respect to what ? do you have an example ? – jhegedus Oct 07 '17 at 16:19
  • @JustinduCoeur Any correct `Future` is `notYet` according to what the readme describes. The API doc on `ExecutionContext` says: "A general purpose ExecutionContext must be asynchronous in executing any Runnable that is passed into its execute-method.". (we have been doing this wrong in SJS with the `runNow` `ExecutionContext`). So the example you give with the `watcher` is IMO a bit bogus since given a correct `ExecutionContext` `watcher.fullyReady` will not be called before `setup` returns (in JS, on the JVM there is an inherent race, with or without `notYet`). – gzm0 Oct 09 '17 at 06:17
  • Huh -- useful to know. `notYet` certainly made a difference when I created it, but that was admittedly a long time ago, and may have been needed against `runNow`... – Justin du Coeur Oct 10 '17 at 12:15