What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?
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);
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);