Florian Baierl
Florian Baierl

Reputation: 2481

Timer that can be used in JVM Scala & Scala.js

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.:

Is there any good alternative or am I wrong and these can be used?

Upvotes: 4

Views: 271

Answers (1)

sjrd
sjrd

Reputation: 22085

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.

Upvotes: 7

Related Questions