What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

karse23 picture karse23 · Jan 27, 2011 · Viewed 96.6k times · Source

Can anyone tell me if an equivalent for setInterval/setTimeout exists for Android? Does anybody have any example about how to do it?

Answer

Ben Clayton picture Ben Clayton · Aug 22, 2013

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().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);