Clock.js 943 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. class Clock {
  2. constructor( autoStart ) {
  3. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4. this.startTime = 0;
  5. this.oldTime = 0;
  6. this.elapsedTime = 0;
  7. this.running = false;
  8. }
  9. start() {
  10. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  11. this.oldTime = this.startTime;
  12. this.elapsedTime = 0;
  13. this.running = true;
  14. }
  15. stop() {
  16. this.getElapsedTime();
  17. this.running = false;
  18. this.autoStart = false;
  19. }
  20. getElapsedTime() {
  21. this.getDelta();
  22. return this.elapsedTime;
  23. }
  24. getDelta() {
  25. let diff = 0;
  26. if ( this.autoStart && ! this.running ) {
  27. this.start();
  28. return 0;
  29. }
  30. if ( this.running ) {
  31. const newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  32. diff = ( newTime - this.oldTime ) / 1000;
  33. this.oldTime = newTime;
  34. this.elapsedTime += diff;
  35. }
  36. return diff;
  37. }
  38. }
  39. export { Clock };