Skip to content

Instantly share code, notes, and snippets.

@gildor
Last active July 23, 2020 02:38
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gildor/e8ef6e1cd1e085ae413ee96b8176883e to your computer and use it in GitHub Desktop.
Save gildor/e8ef6e1cd1e085ae413ee96b8176883e to your computer and use it in GitHub Desktop.
Proof of concept for Kotlin JS coroutines delay()
import kotlin.coroutines.experimental.*
import kotlin.js.Date
fun main(args: Array<String>) {
println("before launch")
launch {
println("hello: ${Date()}")
delay(3000)
println("bye: ${Date()}")
}
println("after launch")
}
fun launch(block: suspend () -> Unit) {
block.startCoroutine(object : Continuation<Unit> {
override val context = EmptyCoroutineContext
override fun resume(value: Unit) = Unit
override fun resumeWithException(exception: Throwable) = console.error(exception)
})
}
suspend fun delay(ms: Long): Unit = suspendCoroutine { continuation ->
setTimeout({
println("timeout")
continuation.resume(Unit)
}, ms)
}
//Use top level setTimeout function instead of window.setTimeout to use with node.js
external fun setTimeout(function: () -> Unit, delay: Long)
//Output example:
//before launch
//hello: Mon Nov 20 2017 16:50:02 GMT+0800 (+08)
//after launch
//timeout
//bye: Mon Nov 20 2017 16:50:05 GMT+0800 (+08)
@pmiklos
Copy link

pmiklos commented Jul 13, 2020

Thanks Andrey, I wish I had found your solution sooner, that would have saved me a couple hours of headache. I couldn't figure out how to use setTimout/setInterval with suspending functions without introducing some kind of deadlock.

@gildor
Copy link
Author

gildor commented Jul 16, 2020

@pmiklos Hah, glad it helped, this is very-very old gist, from times when there was no Kotlinx.Coroutines for JS, now I think it's better to use the official implementation from kotlinx.coroutine, the biggest gain is that it would be cancelable, for now, there is no standard way to make it cancellable without kotlinx.coroutines (at least until the keep about adding cancellation APIs to stdlib will be confirmed)

@pmiklos
Copy link

pmiklos commented Jul 23, 2020

wow, I completely missed that launch is included in kotlinx-coroutines-core-js. The autocomplete wasn't offering it for me so I thought it wasn't implemented or something, but now I realize it's only available inside a CoroutineScope... well, thanks again! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment