What is the equivalent of javascript setTimeout in Java?

"I used the Timer class, but I think that that is not the best way."

The other answers assume you are not using Swing for your user interface (button).

If you are using Swing then do not use Thread.sleep() as it will freeze your Swing application.

Instead you should use a javax.swing.Timer.

See the Java tutorial How to Use Swing Timers and Lesson: Concurrency in Swing for more information and examples.


Asynchronous implementation with JDK 1.8:

public static void setTimeout(Runnable runnable, int delay){
    new Thread(() -> {
        try {
            Thread.sleep(delay);
            runnable.run();
        }
        catch (Exception e){
            System.err.println(e);
        }
    }).start();
}

To call with lambda expression:

setTimeout(() -> System.out.println("test"), 1000);

Or with method reference:

setTimeout(anInstance::aMethod, 1000);

To deal with the current running thread only use a synchronous version:

public static void setTimeoutSync(Runnable runnable, int delay) {
    try {
        Thread.sleep(delay);
        runnable.run();
    }
    catch (Exception e){
        System.err.println(e);
    }
}

Use this with caution in main thread – it will suspend everything after the call until timeout expires and runnable executes.


Using the java.util.Timer:

new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        // here goes your code to delay
    }
}, 300L); // 300 is the delay in millis

Here you can find some info and examples.


Use Java 9 CompletableFuture, every simple:

CompletableFuture.delayedExecutor(5, TimeUnit.SECONDS).execute(() -> {
  // Your code here executes after 5 seconds!
});