ElapsedTime.tsx 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import React, { PureComponent } from 'react';
  2. import { toDuration } from '@grafana/ui/src/utils/moment_wrapper';
  3. const INTERVAL = 150;
  4. export interface Props {
  5. time?: number;
  6. renderCount?: number;
  7. className?: string;
  8. humanize?: boolean;
  9. }
  10. export interface State {
  11. elapsed: number;
  12. }
  13. export default class ElapsedTime extends PureComponent<Props, State> {
  14. offset: number;
  15. timer: number;
  16. state = {
  17. elapsed: 0,
  18. };
  19. start() {
  20. this.offset = Date.now();
  21. this.timer = window.setInterval(this.tick, INTERVAL);
  22. }
  23. tick = () => {
  24. const jetzt = Date.now();
  25. const elapsed = jetzt - this.offset;
  26. this.setState({ elapsed });
  27. };
  28. componentWillReceiveProps(nextProps: Props) {
  29. if (nextProps.time) {
  30. clearInterval(this.timer);
  31. } else if (this.props.time) {
  32. this.start();
  33. }
  34. if (nextProps.renderCount) {
  35. clearInterval(this.timer);
  36. this.start();
  37. }
  38. }
  39. componentDidMount() {
  40. this.start();
  41. }
  42. componentWillUnmount() {
  43. clearInterval(this.timer);
  44. }
  45. render() {
  46. const { elapsed } = this.state;
  47. const { className, time, humanize } = this.props;
  48. const value = (time || elapsed) / 1000;
  49. let displayValue = `${value.toFixed(1)}s`;
  50. if (humanize) {
  51. const duration = toDuration(elapsed);
  52. const hours = duration.hours();
  53. const minutes = duration.minutes();
  54. const seconds = duration.seconds();
  55. displayValue = hours ? `${hours}h ${minutes}m ${seconds}s` : minutes ? ` ${minutes}m ${seconds}s` : `${seconds}s`;
  56. }
  57. return <span className={`elapsed-time ${className}`}>{displayValue}</span>;
  58. }
  59. }