4

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.

thi gg
  • 1,969
  • 2
  • 22
  • 47

3 Answers3

3

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.

madhead
  • 31,729
  • 16
  • 153
  • 201
  • I tried it, but it doesn't work with nodejs, as the package name suggests that works only for browsers. I will update the question – thi gg Aug 03 '19 at 22:31
  • Package is now `kotlinx.browser.window` – Bruno Medeiros Sep 07 '22 at 01:30
  • 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 workers – andylamax Feb 10 '23 at 01:01
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
Nick Bilyk
  • 352
  • 2
  • 8
1

You have

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

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

Koch
  • 555
  • 4
  • 15