2011-12-23 96 views
3

我工作的GWT + JAVA。延迟循环使用GWT定时器

我有一段在GWT代码如下

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

我需要打开多个窗口,允许用户下载的所有文件。

我打电话的servlet。

我如何引入循环延迟,直到下一次迭代?

回答

8

计数器的状态下面是解决方案,在相同的风格MAKS建议通过使用属性保持计数器的状态。你仍然有不同的方式循环。

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); 
} 
+2

GWT定时器不能安排两次 - 至少在第一个预定事件触发之前。调用timer.scheduleRepeating(2000)内部调用cancel(),它取消了第一个调度(500)。 – djjeck 2012-05-23 23:19:03

+0

@djjeck你是对的。答案已更新。谢谢。 – 2012-06-25 13:35:25

+0

+1个不错的工作。今天这帮助了我。 – 2013-04-01 12:19:20

0

你需要调用timer.scheduleRepeating(5000)例如。它会每5秒钟呼叫run方法。你可以写你的运行方式,不会对循环和保存变量

+0

嗨MAKS ..感谢快速回复。我编辑了我的帖子。我延迟了2秒。我需要运行,直到列表大小,这就是为什么我写循环 – 2011-12-23 12:36:32

+0

好吧..我有提示..但是什么时候该停止计时器。你能否提供任何提示 – 2011-12-23 12:45:32