Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

asap.ts 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * MARTINS.js Free Edition
  3. * GPU-accelerated Augmented Reality for the web
  4. * Copyright (C) 2022 Alexandre Martins <alemartf(at)gmail.com>
  5. * https://github.com/alemart/martins-js
  6. *
  7. * This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Affero General Public License version 3
  9. * as published by the Free Software Foundation.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. *
  19. * asap.ts
  20. * Schedule a function to run "as soon as possible"
  21. */
  22. /** callbacks */
  23. const callbacks: Function[] = [];
  24. /** arguments to be passed to the callbacks */
  25. const args: any[][] = [];
  26. /** asap key */
  27. const ASAP_KEY = 'asap' + Math.random().toString(36).substr(1);
  28. // Register an event listener
  29. window.addEventListener('message', event => {
  30. if(event.source !== window || event.data !== ASAP_KEY)
  31. return;
  32. event.stopPropagation();
  33. if(callbacks.length == 0)
  34. return;
  35. const fn = callbacks.pop() as Function;
  36. const argArray = args.pop() as any[];
  37. fn.apply(undefined, argArray);
  38. }, true);
  39. /**
  40. * Schedule a function to run "as soon as possible"
  41. * @param fn callback
  42. * @param params optional parameters
  43. */
  44. export function asap(fn: Function, ...params: any[]): void
  45. {
  46. callbacks.unshift(fn);
  47. args.unshift(params);
  48. window.postMessage(ASAP_KEY, '*');
  49. }