Sleep inside Future in Scala.js
Asked Answered
G

1

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.

Groce answered 7/10, 2017 at 7:50 Comment(2)
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).Tullius
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.Groce
S
7

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")
}
Southward answered 7/10, 2017 at 10:50 Comment(4)
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: github.com/jducoeur/jsextDicotyledon
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 ?Groce
@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).Tullius
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...Dicotyledon

© 2022 - 2024 — McMap. All rights reserved.