Skip to content

Instantly share code, notes, and snippets.

@nondeterministic
Forked from ochrons/WorkerMain.scala
Created February 12, 2018 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nondeterministic/27c8bae401b52d8e0daaf6c7ec08fa94 to your computer and use it in GitHub Desktop.
Save nondeterministic/27c8bae401b52d8e0daaf6c7ec08fa94 to your computer and use it in GitHub Desktop.
Web Worker PoC in Scala.js
<!DOCTYPE html>
<html>
<head>
<title>WW PoC</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div id="root">
</div>
<script type="text/javascript" src="./target/scala-2.11/poc-fastopt.js"></script>
<script type="text/javascript">
Main().main();
</script>
</body>
</html>
package poc
import org.scalajs.dom
import org.scalajs.dom.raw.{Event, Worker}
import scalatags.JsDom.all._
import scala.scalajs.js.annotation.JSExport
import scala.scalajs.js
@JSExport("Main")
object Main {
@JSExport
def main(): Unit = {
val worker = new Worker("worker.js")
var x = 0
val root = dom.document.getElementById("root")
val click: js.Function1[Event, _] = (e: Event) => {
x += 1
if (x > 3) worker.postMessage("Testing")
}
root.appendChild(
div(
h1("Hello!"),
button(id := "post", onclick := click, "Send message")
).render
)
worker.onmessage = (e: js.Any) => {
root.appendChild(div(e.asInstanceOf[dom.MessageEvent].data.asInstanceOf[String]).render)
}
worker.postMessage("Testing")
def nextAnimationFrame(time: Double): Unit = {
dom.window.requestAnimationFrame(nextAnimationFrame _)
// worker.postMessage(s"Time $time")
}
dom.window.requestAnimationFrame(nextAnimationFrame _)
}
}
importScripts("./target/scala-2.11/poc-fastopt.js");
WorkerMain().main();
package poc
import org.scalajs.dom
import scala.scalajs.js
import scala.scalajs.js.annotation.JSExport
@js.native
object WorkerGlobal extends js.GlobalScope {
def addEventListener(`type`: String, f: js.Function): Unit = js.native
def postMessage(data: js.Any): Unit = js.native
}
@JSExport("WorkerMain")
object WorkerMain {
@JSExport
def main(): Unit = {
WorkerGlobal.addEventListener("message", onMessage _ )
WorkerGlobal.postMessage(s"Started")
}
val timeMessage = """Time.*""".r
var count = 0
def onMessage(msg: dom.MessageEvent) = {
val s = msg.data.asInstanceOf[String]
s match {
case timeMessage() =>
count += 1
if(count % 600 == 0)
WorkerGlobal.postMessage("60fps")
case _ =>
WorkerGlobal.postMessage(s"Received: $s")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment