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.js 1.4KB

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