How to Call a Function with a Delay in Kotlin: A Complete Guide with Code

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Why You Need This Right Now

\n

Imagine: you are writing an app, and you need to show a notification to the user 5 seconds after a button is clicked. Or execute a request to the server only 2 seconds after the user has finished typing. Or simply make a nice animation with a delay. Without the ability to call a function with a delay in Kotlin, you won't get far.

\n

This question is one of the most popular on Stack Overflow (thousands of views!), and for good reason. Kotlin has as many as 4 ways to make a delayed call, and each is suitable for its own situation. In this article, we will cover all of them: from the simple delay() in coroutines to the classic Handler for Android. You will learn which method to choose and why, and most importantly, you will see working code that you can immediately copy into your project.

\n\n

Method 1: Coroutines and delay() (Modern and Preferred)

\n

This is the most elegant and recommended way in modern Kotlin. Coroutines are lightweight threads that do not block the main thread. The delay() method suspends the coroutine for a specified time, then resumes it.

\n

To work with coroutines, you need to add a dependency to build.gradle.kts:

\n
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.0")
\n

Here's what it looks like in code:

\n
import kotlinx.coroutines.*\n\nfun main() = runBlocking {\n    println("Start: ${System.currentTimeMillis()}")\n\n    // Launch a coroutine with a delay\n    launch {\n        delay(3000L) // wait 3 seconds\n        println("3 seconds passed: ${System.currentTimeMillis()}")\n        myDelayedFunction() // call the desired function\n    }\n\n    println("Waiting... (this will execute immediately)")\n}\n\nfun myDelayedFunction() {\n    println("Function executed!") \n}
\n

Important: delay() is a suspending function (suspend function). It can only be called inside a coroutine or another suspend function. If you try to call delay() outside a coroutine, the compiler will throw an error.

\n\n

How to Make a Delayed Call in Android with Coroutines

\n

In Android development, coroutines are the de facto standard. Here is an example for an Activity:

\n
import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport kotlinx.coroutines.*\n\nclass MainActivity : AppCompatActivity() {\n\n    private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        setContentView(R.layout.activity_main)\n\n        // Show a toast after 2 seconds\n        scope.launch {\n            delay(2000L)\n            showToast("2 seconds passed!")\n        }\n    }\n\n    private fun showToast(message: String) {\n        android.widget.Toast.makeText(this, message, android.widget.Toast.LENGTH_SHORT).show()\n    }\n\n    override fun onDestroy() {\n        super.onDestroy()\n        scope.cancel() // cancel all tasks when the Activity is destroyed\n    }\n}
\n

Note: we use Dispatchers.Main to work with the UI. And be sure to cancel the scope in onDestroy() to avoid memory leaks.

\n\n

Method 2: Handler and postDelayed() (Android Classic)

\n

If you are writing for Android and don't want (or can't) use coroutines, the good old Handler still works. This method was popular before the era of coroutines.

\n
import android.os.Bundle\nimport android.os.Handler\nimport android.os.Looper\nimport androidx.appcompat.app.AppCompatActivity\n\nclass MainActivity : AppCompatActivity() {\n\n    private val handler = Handler(Looper.getMainLooper())\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        setContentView(R.layout.activity_main)                

Blogs

Book Recommendations