单击GWT中的其他链接后,计时器仍在触发

时间:2014-03-10 20:17:30

标签: gwt timer

所以我有一个计时器,即使我清除了面板并加载了其他模型,它仍然一直在触发...我的问题是,当我卸载模型时如何取消计时器?

所以这是我的代码的一部分

public Display(List<Clarification> result) {

    if (result.size() == 0) {
        Window.alert("EMPTY");
    } else {


        RootPanel.get("Dev1").clear();
         t = new Timer() {
            public void run() {

                cd = new ClarificationDispatcher();
                cd.getClarificationsCount(result.size());
            }
        };
        t.scheduleRepeating(5000);

}

我试图取消Timer onUnload()方法但是,我不相信它会被调用...

谢谢!

1 个答案:

答案 0 :(得分:0)

要遵循的步骤

  • 使用刷新页面时调用的window.onunload事件
  • 首先使用JSNI将cancelTimer()方法导出到java脚本,并将cancelTimerFunction注册为在页面卸载时调用的java脚本函数
  • 取消关闭窗口的计时器

代码:

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;

private static Timer timer = null;

public void onModuleLoad() {
    exportCancelTimer();

    final Label label = new Label("Hello ");
    timer = new Timer() {

        @Override
        public void run() {
            label.setText("Hello " + Math.random() * 100);
        }

    };

    timer.scheduleRepeating(500);
    RootPanel.get().add(label);

    Window.addCloseHandler(new CloseHandler<Window>() {

        @Override
        public void onClose(CloseEvent<Window> event) {
            timer.cancel();
        }
    });

}


public static void cancelTimer() {
    if (timer != null) {
        System.out.println("cancel");
        timer.cancel();
    }
}

public static native void exportCancelTimer() /*-{
    $wnd.cancelTimerFunction = $entry(@com.x.y.z.GWTProject::cancelTimer());
    $wnd.onunload = $wnd.cancelTimerFunction;
}-*/;