19

Is it to use ScalaJS DOM and use the following?

org.scalajs.dom.setTimeout( () => {
  // Work
}, 1000)

Is there another way or a better way within the context of ScalaJS?

sjrd
  • 21,805
  • 2
  • 61
  • 91
Phil
  • 46,436
  • 33
  • 110
  • 175

2 Answers2

32

Starting with Scala.js 0.6.0, there is a more standard way, and more idiomatic Scala, to do it:

import scala.scalajs.js.timers._

setTimeout(1000) { // note the absence of () =>
  // work
}

See the ScalaDoc of timers.

sjrd
  • 21,805
  • 2
  • 61
  • 91
  • Given that the code is not supposed to work in a browser it seems. – Marius K Dec 21 '16 at 06:22
  • 1
    @MariusK What do you mean? The code in my answer works in browsers, in Node.js, and pretty much every other weird JavaScript environment such as electron, etc. – sjrd Dec 21 '16 at 07:22
  • Ah, I read "Non-standard, but in general well supported methods to schedule asynchronous exeuction." and did not find browsers listed in "The methods in this package work in all JavaScript virtual machines supported by Scala.js (currently Rhino, Node.js and PhantomJS).". What is meant by it not being standard? – Marius K Dec 29 '16 at 15:44
  • Is it because it calls setTimeout directly on global scope and not window.setTimeout? – Marius K Dec 29 '16 at 15:55
  • 1
    The code basically works everywhere. I have yet to see a JavaScript environment that does not support `setTimeout`. There's no need to worry: use it and enjoy it. – sjrd Dec 30 '16 at 00:49
1

There isn't a better way. If you want you can wrap it in a helper and call it whatever you want, but by default that's it.

Li Haoyi
  • 15,330
  • 17
  • 80
  • 137