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.
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.Timerimport kotlin.concurrent.scheduleimport kotlin.system.exitProcess// main functionfun main() {println("Starting Timer for 2 secs...")// Delay by 2 secondsTimer().schedule(2000){//calls this function after delaydelayMethod()exitProcess(1)}}// function definationfun delayMethod(){println("Timer is completed.")}
delayMethod()
method after 2
seconds using the Timer
and schedule()
functions.delayMethod()
method.