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.

TimerWorker.ts 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**
  2. * SET_TIMEOUT constant is used to set interval and it is set in
  3. * the id property of the request.data property. TimeMs property must
  4. * also be set.
  5. *
  6. * ```
  7. * //Request.data example:
  8. * {
  9. * id: SET_TIMEOUT,
  10. * timeMs: 33
  11. * }
  12. * ```
  13. */
  14. export const SET_TIMEOUT = 1;
  15. /**
  16. * CLEAR_TIMEOUT constant is used to clear the interval and it is set in
  17. * the id property of the request.data property.
  18. *
  19. * ```
  20. * {
  21. * id: CLEAR_TIMEOUT
  22. * }
  23. * ```
  24. */
  25. export const CLEAR_TIMEOUT = 2;
  26. /**
  27. * TIMEOUT_TICK constant is used as response and it is set in the id property.
  28. *
  29. * ```
  30. * {
  31. * id: TIMEOUT_TICK
  32. * }
  33. * ```
  34. */
  35. export const TIMEOUT_TICK = 3;
  36. /**
  37. * The following code is needed as string to create a URL from a Blob.
  38. * The URL is then passed to a WebWorker. Reason for this is to enable
  39. * use of setInterval that is not throttled when tab is inactive.
  40. */
  41. const code = `
  42. var timer;
  43. onmessage = function(request) {
  44. switch (request.data.id) {
  45. case ${SET_TIMEOUT}: {
  46. timer = setTimeout(() => {
  47. postMessage({ id: ${TIMEOUT_TICK} });
  48. }, request.data.timeMs);
  49. break;
  50. }
  51. case ${CLEAR_TIMEOUT}: {
  52. if (timer) {
  53. clearTimeout(timer);
  54. }
  55. break;
  56. }
  57. }
  58. };
  59. `;
  60. // @ts-ignore
  61. export const timerWorkerScript = URL.createObjectURL(new Blob([ code ], { type: 'application/javascript' }));