How do we call a function after a delay in Kotlin

Overview

In this shot, we will learn how to call a function after a delay in Kotlin.

There is no direct way to achieve this in Kotlin, but we can use Java library functions in Kotlin for this purpose since Kotlin is based on Java. We will use the Timer() and schedule() functions to call a function after a delay.

Let's look at an example of this function.

Example

In the following example, we will call the delayMethod() function after a delay of 2 seconds.

Let's look at the code for the defined example.

import java.util.Timer
import kotlin.concurrent.schedule
import kotlin.system.exitProcess
// main function
fun main() {
println("Starting Timer for 2 secs...")
// Delay by 2 seconds
Timer().schedule(2000){
//calls this function after delay
delayMethod()
exitProcess(1)
}
}
// function defination
fun delayMethod(){
println("Timer is completed.")
}

Explanation

  • Line 8: This line will print when the program execution starts.
  • Lines 11–13: We call the delayMethod() method after 2 seconds using the Timer and schedule() functions.
  • Line 21: We define the delayMethod() method.

Free Resources