I am implementing a function in java that must necessarily wait for a time, similar to javascript's setTimeout, which executes a piece of code after a defined time has elapsed.
For example the following javascript code:
setTimeout(function(){ alert("Hello"); }, 3000);
For now, the closest I've seen is creating a thread and pausing it:
thread.sleep
But I would like to know if there is an easier way.
You can use the Handler class
or the Timer class :
Using Java 9 you can make use of the class
CompletableFuture
:Other than that
Thread.sleep()
you can try using onejavax.swing.Timer
for Java 8, anddelayedExecutor
for newer versions.https://docs.oracle.com/javase/tutorial/uiswing/misc/timer.html https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/CompletableFuture.html
I know of two java.util.Timer classes for scheduling tasks on any type of thread; and if you require it for swing, javax.swing.Timer would be better.
I pass you the links of the documentation of these:
https://docs.oracle.com/javase/8/docs/api/java/util/Timer.html
https://docs.oracle.com/javase/8/docs/api/javax/swing/Timer.html
It is important to mention that swing components should only be updated or called from the event thread. So if you are going to show something through these you have to use the Timer of the swing package or establish the synchronization with the event thread.
For the example you show, it would be something like this: