How to call a function after a delay in Kotlin?



Kotlin is based on Java, hence we can use Java-based library functions to delay a function call. In this article, we will be using a Java library function to delay the function call using Timer() and schedule().

Example

import java.util.Timer import kotlin.concurrent.schedule fun main(args: Array<String>) {    // Execution starting point    println("Hello world!!")    // Delay of 5 sec    Timer().schedule(5000){       //calling a function       newMethod()    } } fun newMethod(){ println("Delayed method call!") }

Output

Once executed, the above piece of code will yield the following output −

Hello world!! Delayed method call!
Updated on: 2021-10-27T11:21:22+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements