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.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.")}
Explanation
- Line 8: This line will print when the program execution starts.
- Lines 11–13: We call the
delayMethod()method after2seconds using theTimerandschedule()functions. - Line 21: We define the
delayMethod()method.