Can anyone tell me if an equivalent for setInterval/setTimeout exists for Android? Does anybody have any example about how to do it?
12 Answers
As always with Android there's lots of ways to do this, but assuming you simply want to run a piece of code a little bit later on the same thread, I use this:
new android.os.Handler(Looper.getMainLooper()).postDelayed(
new Runnable() {
public void run() {
Log.i("tag", "This'll run 300 milliseconds later");
}
},
300);
.. this is pretty much equivalent to
setTimeout(
function() {
console.log("This will run 300 milliseconds later");
},
300);

- 2,895
- 1
- 23
- 25

- 80,996
- 26
- 120
- 129
-
1This is a very good solution for drawer selection and fragmentTransaction – Gonçalo May 26 '15 at 14:48
-
10How can I cancel it if I need to? – Quentin Roy Jun 09 '16 at 08:30
-
How do you obtain the activity scope within the run() method? – Andy Aug 31 '16 at 16:44
-
1@Andy like this: `MyActivityName.this.myFunctionOnActivity()` – Ben Clayton Sep 01 '16 at 11:43
-
2@QuentinRoy: `Handler timeout = new Handler(); final Runnable r = new Runnable{...}; timeout.postDelayed(r, 300);` and if you want to cancel it: `timeout.removeCallbacks(r);` – Bastian Springer Dec 20 '19 at 22:27
setInterval()
function that repeats itself in every n milliseconds
Javascript
setInterval(function(){ Console.log("A Kiss every 5 seconds"); }, 5000);
Approximate java Equivalent
new Timer().scheduleAtFixedRate(new TimerTask(){
@Override
public void run(){
Log.i("tag", "A Kiss every 5 seconds");
}
},0,5000);
setTimeout()
function that works only after n milliseconds
Javascript
setTimeout(function(){ Console.log("A Kiss after 5 seconds"); },5000);
Approximate java Equivalent
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
Log.i("tag","A Kiss after 5 seconds");
}
}, 5000);

- 3,850
- 1
- 23
- 26
-
6For the `scheduleAtFixedRate` method, how do you cancel the timer within the activity once that activity has finished? – auroranil Dec 27 '15 at 05:06
-
3@user824294 you can save your Timer instance in a variable and call "cancel()" when you want to stop the scheduled tasks - Timer t = new Timer(); t.scheduleAtFixedRate(...); - And then call t.cancel(); whenever you wish. – Aebsubis Feb 01 '17 at 14:24
If you're not worried about waking your phone up or bringing your app back from the dead, try:
// Param is optional, to run task on UI thread.
Handler handler = new Handler(Looper.getMainLooper());
Runnable runnable = new Runnable() {
@Override
public void run() {
// Do the task...
handler.postDelayed(this, milliseconds) // Optional, to repeat the task.
}
};
handler.postDelayed(runnable, milliseconds);
// Stop a repeating task like this.
handler.removeCallbacks(runnable);

- 76,500
- 11
- 62
- 80

- 11,399
- 5
- 51
- 42
-
On my phone (Huawei P Smart) the Handler does not wake up the device from sleep mode ([as remarked by apanloco in another answer](https://stackoverflow.com/a/4819256/659788)) – Franco Jun 29 '20 at 22:21
Depending on what you actually want to achieve, you should take a look at Android Handlers:
http://developer.android.com/reference/android/os/Handler.html
If you previously used javascript setTimeout() etc to schedule a task to run in the future, this is the Android way of doing it (postDelayed / sendMessageDelayed).
Note that neither Handlers or Timers makes an Android phone wake up from sleep mode. In other words, if you want to schedule something to actually happen even though the screen is off / cpu is sleeping, you need to check out the AlarmManager too.

- 175
- 1
- 8
The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:
this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);

- 465
- 6
- 11
import java.util.Timer;
import java.util.TimerTask;
class Clock {
private Timer mTimer = new Timer();
private int mSecondsPassed = 0;
private TimerTask mTask = new TimerTask() {
@Override
public void run() {
mSecondsPassed++;
System.out.println("Seconds passed: " + mSecondsPassed);
}
};
private void start() {
mTimer.scheduleAtFixedRate(mTask, 1000, 1000);
}
public static void main(String[] args) {
Clock c = new Clock();
c.start();
}
}

- 1,029
- 3
- 15
- 21
I do not know much about JavaScript, but I think Timers may be what you are looking for.
http://developer.android.com/reference/java/util/Timer.html
From the link:
One-shot are scheduled to run at an absolute time or after a relative delay. Recurring tasks are scheduled with either a fixed period or a fixed rate.

- 42,483
- 9
- 127
- 120
-
-
This isn't an answer, but a reference to external information that may or may not even contain OPs solution. Please paste in the relevant code OP can use! – SikoSoft Nov 03 '14 at 14:29
I was creating a mp3 player for android, I wanted to update the current time every 500ms so I did it like this
setInterval
private void update() {
new android.os.Handler().postDelayed(new Runnable() {
@Override
public void run() {
long cur = player.getCurrentPosition();
long dur = player.getDuration();
currentTime = millisecondsToTime(cur);
currentTimeView.setText(currentTime);
if (cur < dur) {
updatePlayer();
}
// update seekbar
seekBar.setProgress( (int) Math.round((float)cur / (float)dur * 100f));
}
}, 500);
}
which calls the same method recursively
Here's a setTimeout equivalent, mostly useful when trying to update the User Interface after a delay.
As you may know, updating the user interface can only by done from the UI thread. AsyncTask does that for you by calling its onPostExecute method from that thread.
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// Update the User Interface
}
}.execute();

- 1,413
- 15
- 14
-
3**1.** Similarly, `onProgressUpdate()` can also be used to simulate `setInterval()`. **2.** `AsyncTask` runs on a thread pool (or just a single thread), so *a.* it may have to wait until another `AsyncTask` finishes; *b*. it will take up one thread from the pool. – Pang Jan 29 '13 at 05:34
-
There are a lot of issues using async task in this context (only one thread and the locking of a thread for no reason) - the other solutions are much better. – Elemental Feb 28 '18 at 14:29
As always with Android there's lots of ways to do this, but assuming you simply want to run a piece of code on the same thread, I use this:
new Timer().scheduleAtFixedRate(new TimerTask(){
@Override
public void run(){
Log.i("tag", "Hai Codemaker");
}
},0,1000);
This code will log Hai Codemaker text every one second.

- 12,190
- 6
- 97
- 81
Kotlin:
You can also use CountDownTimer:
class Timer {
companion object {
@JvmStatic
fun call(ms: Long, f: () -> Unit) {
object : CountDownTimer(ms,ms){
override fun onFinish() { f() }
override fun onTick(millisUntilFinished: Long) {}
}.start()
}
}
}
And in your code:
Timer.call(5000) { /*Whatever you want to execute after 5000 ms*/ }

- 1,225
- 15
- 27
In case someone wants -
Kotlin equivalent to JavaScript setInterval/setTimeout
IMPORTANT: Remember to import android.os.Handler
. Don't get mistaken by java.util.logging.Handler
Timeout equivalent
Javascript: setTimeout()
setTimeout(function(){
// something that can be run.
}, 1500);
Kotlin: runOnTimeout()
inline fun runOnTimeout(crossinline block: () -> Unit, timeoutMillis: Long) {
Handler(Looper.getMainLooper()).postDelayed({
block()
}, timeoutMillis)
}
Kotlin: Calling
runOnTimeout({
// something that can be run.
}, 1500)
Timeinterval equivalent
Javascript: setInterval()
setInterval(function(){
// something that can be run.
}, 1500);
Kotlin: runOnInterval()
inline fun runOnInterval(crossinline block: () -> Unit, interval: Long) {
val runnable = object : Runnable {
override fun run() {
block()
handler.postDelayed(this, interval)
}
}
handler.post(runnable)
}
Kotlin: Calling
runOnInterval({
// something that can be run.
}, 1500)
Cancellable timeout and interval
If you want to use custom handler so that you can cancel the runnable, then you can use following codes.
Timeout
inline fun runOnTimeout(crossinline block: () -> Unit, timeoutMillis: Long) {
runOnTimeout(Handler(Looper.getMainLooper()), block, timeoutMillis)
}
inline fun runOnTimeout(handler: Handler, crossinline block: () -> Unit, timeoutMillis: Long): Runnable {
val runnable = Runnable { block() }
handler.postDelayed(runnable, timeoutMillis)
return runnable
}
Timeout: Calling
runOnTimeout({
// something that can be run.
}, 1500)
// OR
val runnable = runOnTimeout(mHandler, {
// something that can be run.
}, 1500)
// to cancel
mHandler.removeCallbacks(runnable)
Interval
inline fun runOnInterval(crossinline block: () -> Unit, interval: Long) {
runOnInterval(Handler(Looper.getMainLooper()), block, interval)
}
inline fun runOnInterval(handler: Handler, crossinline block: () -> Unit, interval: Long): Runnable {
val runnable = object : Runnable {
override fun run() {
block()
handler.postDelayed(this, interval)
}
}
handler.post(runnable)
return runnable
}
Interval: Calling
runOnInterval({
// something that can be run.
}, 1500)
// OR
val runnable = runOnInterval(mHandler, {
// something that can be run.
}, 1500)
// to cancel
mHandler.removeCallbacks(runnable)

- 548
- 3
- 16