Hello, is there more idiomatic way with coroutines...
# javascript
g
Hello, is there more idiomatic way with coroutines for something like this?
Copy code
launch {
            while (true) {
                context.clearRect(
                    0.0,
                    0.0,
                    context.canvas.width.toDouble(),
                    context.canvas.height.toDouble()
                )
                draw(context)
                delay(1000 / 60)
            }
        }
n
Best to ask in #coroutines
u
You can use setTimeout
g
Thanks, I had no idea there is such channel. Well, I started with setTimeout, but coroutines seems to me as better solution
u
Great. Then go for it.
I don't know how accurate you are aiming for 60fps. But be aware, that in your code errors accumulate. Each loop will take somewhat longer then the 1/60th second. And sooner or later you will miss one frame
With coroutines, you could also make the drawing code an actor and send a command to it every 1/60th second. But i think the launch is ok
g
It's simple tick-tack-toe in browser, so it doesn't matter, but thanks for tip, it will be useful in future for something more complex
b
I’d advice to use
window.requestAnimationFrame
to get better UX. And with
kotlinx-coroutines-core-js
you can use
window.awaitAnimationFrame()
like here https://github.com/Kotlin/kotlinx.coroutines/blob/5f2e94b7631616683eb7b8aec00e8cf4a594a299/js/example-frontend-js/src/main/kotlin/ExampleMain.kt#L198