How do I call JS functions like setTimeout in Kotlin when not targeting browsers
Asked Answered
B

3

5

Do I have to define them externally like so:

external fun setTimeout(exec: suspend () -> Unit, timout: Int)

Or is there something in the stdlib I can use?

I can't use kotlin.browser.window.setTimeout because I want to run it with nodejs.

Bullnose answered 3/8, 2019 at 21:45 Comment(0)
M
4

There is already a setTimeout function in kotlin-stdlib-js. You don't need to declare it externally. The usage is pretty straightforward:

import kotlin.browser.window

fun main() {
    window.setTimeout(handler = { window.alert("Timed out!") }, timeout = 1000)
}

This will alert you (another well-known JS function) after 1 second, as expected.

Marolda answered 3/8, 2019 at 22:4 Comment(3)
I tried it, but it doesn't work with nodejs, as the package name suggests that works only for browsers. I will update the questionBullnose
Package is now kotlinx.browser.windowTernate
this will only work on browsers and no where else, because it is trying to access setTimeout from the window object, which is usually undefined on nodejs and even service workersBarone
S
2

It's definitely not in the stdlib. I'm doing the same thing, defining the external functions I need.

external fun setTimeout(handler: dynamic, timeout: Int = definedExternally, vararg arguments: Any?): Int
Stereo answered 18/9, 2019 at 16:46 Comment(0)
D
2

You have

external fun setTimeout(
    callback: () -> Unit,
    ms: Int = definedExternally,
): Timeout

and you can use it like this : setTimeout({ if(someCondition) doSomething() }, 3000)

Decontaminate answered 20/1, 2023 at 20:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.