Search code examples
javadelay

Making a delay without try/catch, or having it in one function


I want to make my simple applet as least cluttered as possible. Currently all my delays are like

try
{
    TimeUnit.SECONDS.sleep(1);
}
catch(InterruptedException e)
{
}

but its really cluttered. I want to have some sort of function, such as

try
{
    TimeUnit.SECONDS.sleep(Delay);
}
catch(InterruptedException e)
{
}

then have it get called like this somehow

delay(3)

Or, just get rid of the try/catch statement in general. Is that possible?


Solution

  • Just create a method that swallows the try/catch.

    public void timeDelay(long t) {
        try {
            Thread.sleep(t);
        } catch (InterruptedException e) {}
    }
    

    Anytime you want to sleep, call the method.

    public void myMethod() {
        someCodeHere();
        timeDelay(2000);
        moreCodeHere();
    }