ElapsedTime.tsx 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import React, { PureComponent } from 'react';
  2. import { toDuration } from '@grafana/data';
  3. const INTERVAL = 150;
  4. export interface Props {
  5. time?: number;
  6. // Use this to reset the timer. Any value is allowed just need to be !== from the previous.
  7. // Keep in mind things like [] !== [] or {} !== {}.
  8. resetKey?: any;
  9. className?: string;
  10. humanize?: boolean;
  11. }
  12. export interface State {
  13. elapsed: number;
  14. }
  15. /**
  16. * Shows an incremental time ticker of elapsed time from some event.
  17. */
  18. export default class ElapsedTime extends PureComponent<Props, State> {
  19. offset: number;
  20. timer: number;
  21. state = {
  22. elapsed: 0,
  23. };
  24. start() {
  25. this.offset = Date.now();
  26. this.timer = window.setInterval(this.tick, INTERVAL);
  27. }
  28. tick = () => {
  29. const jetzt = Date.now();
  30. const elapsed = jetzt - this.offset;
  31. this.setState({ elapsed });
  32. };
  33. UNSAFE_componentWillReceiveProps(nextProps: Props) {
  34. if (nextProps.time) {
  35. clearInterval(this.timer);
  36. } else if (this.props.time) {
  37. this.start();
  38. }
  39. if (nextProps.resetKey !== this.props.resetKey) {
  40. clearInterval(this.timer);
  41. this.start();
  42. }
  43. }
  44. componentDidMount() {
  45. this.start();
  46. }
  47. componentWillUnmount() {
  48. clearInterval(this.timer);
  49. }
  50. render() {
  51. const { elapsed } = this.state;
  52. const { className, time, humanize } = this.props;
  53. const value = (time || elapsed) / 1000;
  54. let displayValue = `${value.toFixed(1)}s`;
  55. if (humanize) {
  56. const duration = toDuration(elapsed);
  57. const hours = duration.hours();
  58. const minutes = duration.minutes();
  59. const seconds = duration.seconds();
  60. displayValue = hours ? `${hours}h ${minutes}m ${seconds}s` : minutes ? ` ${minutes}m ${seconds}s` : `${seconds}s`;
  61. }
  62. return <span className={`elapsed-time ${className}`}>{displayValue}</span>;
  63. }
  64. }