Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set timeout for user's input

Tags:

java

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.
like image 965
Артём Царионов Avatar asked Apr 07 '12 23:04

Артём Царионов


People also ask

What is setTimeout() in JavaScript?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

How do I create a timeout in JavaScript?

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);

What window method is used to delay an action for a set number of milliseconds why might this method be useful?

The setTimeout() method calls a function after a number of milliseconds. 1 second = 1000 milliseconds.


1 Answers

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.

like image 91
Jeffrey Avatar answered Oct 25 '22 03:10

Jeffrey