-1

I need a variable to count upwards but in increments of 2 seconds. Right now I'm simply using a ++; function, but as you know it's extremely fast.

Is there anything simple I can use to count at a slower pace?

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
Hoberfinkle
  • 35
  • 1
  • 7
  • 3
    `Thread.sleep( 2000 )` but it is not precise. You probably want something more like a `Timer` – clcto Dec 14 '13 at 00:11
  • Agree with @clcto, You should read [Java: How to use Timer class to call a method, do something, reset timer, repeat?](http://stackoverflow.com/questions/9413656/java-how-to-use-timer-class-to-call-a-method-do-something-reset-timer-repeat), could be help to you. – Smit Dec 14 '13 at 00:15

4 Answers4

1
Thread.sleep(2000);

This will make your program to wait for 2 seconds between this method call and whatever line of execution immediately follows this.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
1
public class Count implements Runnable{
  public void run(){
     for(int i=0;i<=6;i+=2){
         Thread.sleep(2000)//in milliseconds ...sleeping for 2 sec
         sysout(...);//print your value
       }
   }
}

Start it this way

Runnable r=new Count();
Thread t=new Thread(r);
t.start(); // start the  thread

What you doing is basicly making a thread and running with a delay.I hope you get a concept

Tomas Bisciak
  • 2,801
  • 5
  • 33
  • 57
0

Yes, you can pause the execution for two seconds by using Thread.sleep(2000).

//Your code...
Thread.sleep(2000);
counter = counter + 2;
//Your code...
SerotoninChase
  • 424
  • 11
  • 28
0

This will print from 1 to 99, incrementing by 2 with a one second pause between increments.

public static void main(String[] args) {
  for (int i = 1; i < 100; i += 2) { // i = i + 2
    System.out.printf("i = %d\n", i); // print i = #
    try {
      Thread.sleep(2000); // two seconds.
    } catch (InterruptedException e) {
    }
  }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249