Hardik Mishra
Hardik Mishra

Reputation: 14877

Delay in Loop Using GWT Timer

I am working on GWT + JAVA.

I have a piece of code in GWT as below

static int DELAY = 1000;

private void downloadAttachments(final List<String> ftIdList) 
{
   try
   {
      Timer timer = new Timer() 
      {
         @Override
         public void run() 
         {
            int cnt = 1;
            for (String url: ftIdList)
            {
               String windowName = "win" + cnt;
               Window.open(url, windowName, "");
               cnt++;
               scheduleRepeating(DELAY*2);
            }
            cancel();
         }
      };
      timer.run();
   }
   catch (Throwable exc) 
   {
      Window.alert(exc.getMessage());
   }
} 

I need to open several windows to allow a user to download all files.

I am calling a Servlet.

How can I introduce a delay in the loop until the next iteration?

Upvotes: 3

Views: 8517

Answers (2)

Goran Nastov
Goran Nastov

Reputation: 985

Here is solution, in same style as maks suggests by using property for keeping the state of the counter. You still have the loop just in different way.

private void downloadAttachments(final List<String> ftIdList) {
    final int size = ftIdList.size();

    Timer timer = new Timer() {

        private int counter = 0;

        @Override
        public void run() {
        if (counter == size) {
          cancel();
          return;
        }
        String url = ftIdList.get(counter);
        String winName = "win" + counter;
        Window.open(url, winName, "");
        counter++;
        }
    };
    timer.scheduleRepeating(2000);
}

Upvotes: 8

maks
maks

Reputation: 6006

You need to call timer.scheduleRepeating(5000) for example. It will call run method each 5 seconds. You can write your run method as without for loop and save the state of counters in variables

Upvotes: 0

Related Questions