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.

TimeWorker.js 1.4KB

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