No setTimeout, setInterval, clearTimeout, clearInterval in kotlin

Gotcha, so you’re using Kotlin/JVM (or more specifically, Kotlin on Android) but would prefer a pure Kotlin solution.

On JVM, you can use all of the same solutions for Java and Android found here.
There is likely a newer solution for Android that uses coroutines that I don’t know of. Maybe someone knows if there is some other preferred method for Android?

If you were developing an app in a specific framework (e.x. SpringBoot), the framework may likely provide a way of scheduling tasks. Don’t hesitate to use a solution for your specific scenario. Kotlin is meant to work along side your existing platform so JVM and Android solutions are just as valid as multi-platform Kotlin solutions.


A Kotlin solution that works on JVM, JS, Android, iOS, and other native targets is possible using Coroutines. This might be more than you want at this time though.

Here’s a crude implementation that uses coroutines:

import kotlinx.coroutines.*

fun setInterval(timeMillis: Long, handler: () -> Unit) = GlobalScope.launch {
    while (true) {
        delay(timeMillis)
        handler()
    }
}

fun main() {
    var count = 0
    
    setInterval(500) {
        println("Count=$count")
        count++
    }
    
    Thread.sleep(3000) // Keep the program from exiting for a few seconds.
}

It’s pretty unsafe in the concurrent sense (equally as unsafe as setInterval in JS). In Kotlin, we have structured concurrency and coroutines to do this better.
Here’s the link to the coroutines overview which has links to more info and tutorials.

1 Like