The setInterval method has the same syntax as setTimeout : let timerId = setInterval(func|code, [delay], [arg1], [arg2], ...) All arguments have the same meaning. But unlike setTimeout it runs the function not only once, but regularly after the given interval of time.
long startTime = System. currentTimeMillis(); // .. do stuff .. long elapsed = System. currentTimeMillis()-startTime; if (elapsed>timeout) throw new RuntimeException("tiomeout");
We all know that passing a string to setTimeout (or setInterval ) is evil, because it is run in the global scope, has performance issues, is potentially insecure if you're injecting any parameters, etc. So doing this is definitely deprecated: setTimeout('doSomething(someVar)', 10000);
setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
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.
Use Java 9 CompletableFuture, every simple:
CompletableFuture.delayedExecutor(5, TimeUnit.SECONDS).execute(() -> {
// Your code here executes after 5 seconds!
});
"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.
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.
You can simply use Thread.sleep()
for this purpose. But if you are working in a multithreaded environment with a user interface, you would want to perform this in the separate thread to avoid the sleep to block the user interface.
try{
Thread.sleep(60000);
// Then do something meaningful...
}catch(InterruptedException e){
e.printStackTrace();
}
Do not use Thread.sleep
or it will freeze your main thread and not simulate setTimeout from JS. You need to create and start a new background thread to run your code without stoping the execution of the main thread. Like this:
new Thread() {
@Override
public void run() {
try {
this.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// your code here
}
}.start();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With