Billy Moon
Billy Moon

Reputation: 58601

Java equivalent of JavaScript Timeout functions

I am translating some Javascript code into Java, and need to know how to do Timeouts in Java. How would I translate the following into Java?

var x = setTimeout(function(){ ... }, 2000);
clearTimeout(x);

Upvotes: 3

Views: 2246

Answers (3)

cabreracanal
cabreracanal

Reputation: 934

Try out with java.util.Timer

You can schedule your task when the specified time is over or into a periodic interval. Use

myTimer.schedule(tt, 2000);

where tt is a TimerTask object from java.util.TimerTask (you have to implement the run() method, who will correspond to your "function(){ ... }" in javascript).

Upvotes: 4

Ved
Ved

Reputation: 8767

Create a thread and paste your business logic (in which you want to wait). Then use Thread.sleep(2000);. However it is depending on your needs that what exactly you want to do with your java code. Also you can use public interface Lock like this :

 Lock lock = ...;
  if ( lock.tryLock(50L, TimeUnit.SECONDS) ) ...

Upvotes: 0

SJuan76
SJuan76

Reputation: 24895

Create a Launch a new Thread. In case you need a delay in the execution, you can use sleep()

Anyway it is basically different, in JS you do not have a 'Main thread' (JS is run by the browser threads) while in Java you have it. So, if what you want to do is to call a function separately at specified times, you create just one thread and in this thread you make a loop with sleep and your logic (and mark the thread as daemon).

Upvotes: 0

Related Questions