timeout.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /**
  2. * This file is part of Threema Web.
  3. *
  4. * Threema Web is free software: you can redistribute it and/or modify it
  5. * under the terms of the GNU Affero General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or (at
  7. * your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
  12. * General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Affero General Public License
  15. * along with Threema Web. If not, see <http://www.gnu.org/licenses/>.
  16. */
  17. export class TimeoutService {
  18. private logTag: string = '[TimeoutService]';
  19. // Angular services
  20. private $log: ng.ILogService;
  21. private $timeout: ng.ITimeoutService;
  22. // List of registered timeouts
  23. private timeouts: Set<ng.IPromise<any>> = new Set();
  24. public static $inject = ['$log', '$timeout'];
  25. constructor($log: ng.ILogService, $timeout: ng.ITimeoutService) {
  26. // Angular services
  27. this.$log = $log;
  28. this.$timeout = $timeout;
  29. }
  30. /**
  31. * Register a timeout.
  32. */
  33. public register<T>(fn: (...args: any[]) => T, delay: number, invokeApply: boolean): ng.IPromise<T> {
  34. this.$log.debug(this.logTag, 'Registering timeout');
  35. const timeout = this.$timeout(fn, delay, invokeApply);
  36. timeout.finally(() => this.timeouts.delete(timeout));
  37. this.timeouts.add(timeout);
  38. return timeout;
  39. }
  40. /**
  41. * Cancel the specified timeout.
  42. *
  43. * Return true if the task hasn't executed yet and was successfully canceled.
  44. */
  45. public cancel<T>(timeout: ng.IPromise<T>): boolean {
  46. this.$log.debug(this.logTag, 'Cancelling timeout');
  47. const cancelled = this.$timeout.cancel(timeout);
  48. this.timeouts.delete(timeout);
  49. return cancelled;
  50. }
  51. /**
  52. * Cancel all pending timeouts.
  53. */
  54. public cancelAll() {
  55. this.$log.debug(this.logTag, 'Cancelling all timeouts');
  56. for (const timeout of this.timeouts) {
  57. this.$timeout.cancel(timeout);
  58. }
  59. this.timeouts.clear();
  60. }
  61. }