AnimationTimer.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /**
  2. * Animation timer should be used to run the update and render loops of the application.
  3. *
  4. * Underneat it uses the requestAnimationFrame() method that calls the function with the same rate as the screen refresh rate.
  5. *
  6. * @class
  7. * @param {Function} callback Timer callback function.
  8. */
  9. function AnimationTimer(callback)
  10. {
  11. /**
  12. * Task of the timer, executed at the timer defined rate.
  13. *
  14. * @type {Function}
  15. */
  16. this.callback = callback;
  17. /**
  18. * Indicates if the timer is currently running, it is set to true on start and reset to false on stop.
  19. *
  20. * @type {boolean}
  21. */
  22. this.running = false;
  23. /**
  24. * ID of the currently waiting timeout clock. Used to cancel the already request execution of the next clock tick.
  25. *
  26. * @type {number}
  27. */
  28. this.id = -1;
  29. }
  30. /**
  31. * Start timer, is the timer is already running does not do anything.
  32. */
  33. AnimationTimer.prototype.start = function()
  34. {
  35. if(this.running)
  36. {
  37. return;
  38. }
  39. this.running = true;
  40. var self = this;
  41. function loop()
  42. {
  43. self.callback();
  44. if(self.running)
  45. {
  46. self.id = requestAnimationFrame(loop);
  47. }
  48. }
  49. loop();
  50. };
  51. /**
  52. * Stop animation timer, should be called when the render loop is no longer in use to prevent code/memory leaks.
  53. *
  54. * If the timer is not stopped the loop will keep running using processing power and consuming memory.
  55. */
  56. AnimationTimer.prototype.stop = function()
  57. {
  58. this.running = false;
  59. cancelAnimationFrame(this.id);
  60. };
  61. export {AnimationTimer};