At the moment I am working on a project that is cross-compiled to Scala.js and normal JVM Scala. Now I need to implement a timer (for reconnecting a websocket) that triggers a function every x seconds. What would be a good implementation of such a timer that can be cross compiled?
As far as I know I cannot use e.g.:
java.util.concurrent
(doesn't compile to Scala.js)setTimeout
and setInterval
(javascript - not usable from JVM Scala)Is there any good alternative or am I wrong and these can be used?
java.util.Timer
is supported by Scala.js, and provides exactly the functionality you're describing:
val x: Long = seconds
val timer = new java.util.Timer()
timer.scheduleAtFixedRate(new java.util.TimerTask {
def run(): Unit = {
// this will be executed every x seconds
}
}, 0L, x * 1000L)
Consult the JavaDoc that I linked above for details about the API.
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