No setTimeout, setInterval, clearTimeout, clearInterval in kotlin

When i use the search for setInterval on kotlin page it leads me to a JavaScript

Is there no kotlin solution?

The dom API is available in Kotlin/JS so you are free to call setInterval like you normally would.

Which platform are you developing on?

Well basicly i don’t want to use JS. Pure kotlin (Java) if possible.
Android Studio is was my choice

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

Thank you @arocnies

Just one more question.

First of all, you were right. https://kotlinlang.org/docs/reference/coroutines/cancellation-and-timeouts.html
Amazing

But for my special case i should set a boolean to my element.

Let’s say i’ll create something like this

myElement.onEnterFrame({
//do something and repeat till this.deleteOnEnterFrame
})

Yes, both functionnames are actionscript (if you are familiar with that, for better understanding)
If not, this is the explanation

If i want my repeats run as long as needed, i need a val or var to cancel it.
Doesn’t make sence to use a local or global var. Better way is e.g.

this.goAhead:Boolean=true

and within my within my launch i need something to check that boolean

if i set this.goAhead to false, launch should be canceled.

Is there anyway to set vars or vals to elements?

this.something of course isn’t working

By convention, if you are using a val you should not really be doing anything but trivially getting or setting some simple data. Properties are intended for very simple access to data. Anything more complicated like managing coroutines should be implemented with methods.

So you could specify custom get/set implementation on a goAhead property to so, but you shouldn’t. See the docs on custom get/set implementation on what’s possible with properties: Properties and Fields

The launch method returns a Job which has a cancel method. When you start the timer save off the job in a property and when you want to stop the timer, just cancel it.

Got you.
But that’s the point (or issue)

I try to to develop a game (some balls falling down and so on)

of course i want to stop each routine (cancel) for each ball when it has reached his y value. An i create this balls dynamically. So there is no way to just use one function (e.g. job) an cancel that.

I guess this makes it easier to understand.

The easiest way is something like

myBall1.onRun:true and myBall1.onRun=false

Best way to describe my Problem is using an Javascript example (Only as example)

document.getElementById('mydiv').intval=setInterval(
  function(){
       //dosomething
 }
,500);

//and whenever i want
clearInterval(document.getElementById('mydiv').intval)

Adding values to existing classes

It sounds like you’re asking if you can add a variable to an object. This isn’t possible in Kotlin.

You can modify your class to include that property:

class Name(val value: String)
// Rewritten to include a nickname
class Name(val value: String, val nickName: String)

You can always keep a map of objects to a value that you wish to be associated with them. For example:

class Name(val value: String)

val nickNames: Map<String, String>
nickNames += Name("Richard") to "Rick"
nickNames += Name("Cassidy") to "Cas"

You can also create extension properties:

class Name(val value: String)

val Name.nickName get() = "some calculated value from $this"

And you can wrap your object:

class Name(val value: String)

class NameWithNickName(name: Name, val nickname: String) {
    val value: String = name.value
}

But it’s not possible to add a member to a class afterwards like this:

class Name(val value: String)

val michael = Name("Micheal")
michael.nickname = "Mike" // Not possible. There is since the Name class does not have a nickname!

There are many other ways and software design patterns you could use. But any given object isn’t a mutable map of values like it is in Javascript. Member variables and functions can’t be changed on an object.

Canceling Jobs

There’s too much to go into detail about here on the forum. I’ll try to give a simple idea for now but after you’ve gotten comfortable with Kotlin you’ll want to go through the coroutine guide.

If all you want to do is stop the looping job you’ve created, you can change the setInterval function to leave the while loop on some condition. You can use a global value for this or just make the loop stop on a specific value from your game (like the y of a ball).
This solution means we don’t do anything special coroutine related. You could do this exact same thing with launching threads:

thread(start = true) {
    // code that runs in another thread
}

Globals

It is a bad idea to use global things in general. But while you’re learning I think it’s fine. Eventually, you’ll understand the reasons behind globals being bad design and where those values should go instead. But don’t let that slow you down from getting code running before then.

It’ll be well worth your time to go through some docs.
The Kotlin hands-on are a bit advanced for beginners but I still recommend them for this kind of learning. The reference is great as you can edit the code directly on the site to experiment and if you want to reinforce what you learn there, you can use the Kotlin Koans.

A pitty
Though i could do a similar thing as i did with my prototypes.
Hmmmmm.

Well, i try to figure something out

To elaborate on this a bit: a property getter or setter shouldn’t usually do anything that would surprise the caller, who is expecting it to behave roughly like a simple field access.⠀ Of course, you can do a bit more than that, such as:

  • Convert the value to/from an internal format.â € (This is probably the most important reason for using accessor methods in the first place: it avoids tying you down to a particular internal representation.)
  • Get the value from (or set it on) some other object.
  • Calculate the value (and maybe cache it).
  • Log the change.

You might also think it OK (if properly documented) to:

  • Check any constraints on the value and/or class invariants, and either change the value or throw an exception if any would be violated.
  • Notify any observers of the change.

However, the caller would probably not be expecting a getter or setter to do anything like:

  • Change the visible state of the object (except, for a setter, directly related to the property being set), or of apparently-unrelated objects.
  • Take a substantial amount of time before returning. (Triggering processing on other threads, without blocking the calling thread, might be OK, though.)

If you need to do any of the latter, it’s probably better to make it a method instead, where such things would be less surprising.

1 Like

Thank you

That’s a bit to high yet for my brain. But definately on my list to read, try, understand and save on my "soft"drive (Brain)

Thank you very much

For now i did it with a class

class timer{
///My intervall and stop code
}

Works, but it’s not the cleanest way.