How to create a Java function which Once called, cannot be called Again unless there is some DELAY?

android, java

Solution

You could hold the time in milliseconds and check if the current time is greater than or equal to the previous time + 5 seconds. If it is, execute the method and replace the previous time with the current time.

See System.currentTimeMillis()

public class FiveSeconds {
    private static Scanner scanner = new Scanner(System.in);
    private static long lastTime = 0;

    public static void main(String[] args) {    
        String input = scanner.nextLine();

        while(!input.equalsIgnoreCase("quit")){
            if(isValidAction()){
                System.out.println(input);
                lastTime = System.currentTimeMillis();
            } else {
                System.out.println("You are not allowed to do this yet");
            }

            input = scanner.nextLine();
        }       
    }

    private static boolean isValidAction(){
        return(System.currentTimeMillis() > (lastTime + 5000));
    }
}

Problem

I'm trying to make a function which can ONLY be called again after there is some amount of time delay between the two calls, (Say 5 seconds). I require this functionality for an android app I'm creating. Since it is possible that the user would be calling that function too frequently within a few seconds, it would destroy his experience. Hence, I'm desperately looking for an answer on this. ``` public void doSomethin(){ //code here which makes sure that this function has not been called twice within the specified delay of 5 seconds //Some code here } ``` Any help would be awesome! Adit

Original source