Search code examples
javascalatimerscala.js

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

  • 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?


Solution

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