Is it possible to set timer for user's input? Wait 10 seconds - do next operation and etc. I mean for example
//wait several seconds{
String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
//wait server seconds}
//next operation and etc.
setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout(function, milliseconds);
The setTimeout() method calls a function after a number of milliseconds. 1 second = 1000 milliseconds.
A slightly easier way to do this than Benjamin Cox's answer would be to do something like
int x = 2; // wait 2 seconds at most
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
long startTime = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime) < x * 1000
&& !in.ready()) {
}
if (in.ready()) {
System.out.println("You entered: " + in.readLine());
} else {
System.out.println("You did not enter data");
}
This will, however consume more resources than his solution.
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