You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

VLazyExecutor.java 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright 2000-2018 Vaadin Ltd.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  5. * use this file except in compliance with the License. You may obtain a copy of
  6. * the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations under
  14. * the License.
  15. */
  16. package com.vaadin.client.ui;
  17. import com.google.gwt.core.client.Scheduler.ScheduledCommand;
  18. import com.google.gwt.user.client.Timer;
  19. /**
  20. * Executes the given command {@code delayMs} milliseconds after a call to
  21. * {@link #trigger()}. Calling {@link #trigger()} again before the command has
  22. * been executed causes the execution to be rescheduled to {@code delayMs} after
  23. * the second call.
  24. *
  25. */
  26. public class VLazyExecutor {
  27. private Timer timer;
  28. private int delayMs;
  29. private ScheduledCommand cmd;
  30. /**
  31. * @param delayMs
  32. * Delay in milliseconds to wait before executing the command
  33. * @param cmd
  34. * The command to execute
  35. */
  36. public VLazyExecutor(int delayMs, ScheduledCommand cmd) {
  37. this.delayMs = delayMs;
  38. this.cmd = cmd;
  39. }
  40. /**
  41. * Triggers execution of the command. Each call reschedules any existing
  42. * execution to {@link #delayMs} milliseconds from that point in time.
  43. */
  44. public void trigger() {
  45. if (timer == null) {
  46. timer = new Timer() {
  47. @Override
  48. public void run() {
  49. timer = null;
  50. cmd.execute();
  51. }
  52. };
  53. }
  54. // Schedule automatically cancels any old schedule
  55. timer.schedule(delayMs);
  56. }
  57. }