SetInterval.tsx 939 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { PureComponent } from 'react';
  2. import { stringToMs } from '../../utils/string';
  3. interface Props {
  4. func: () => any; // TODO
  5. interval: string;
  6. }
  7. export class SetInterval extends PureComponent<Props> {
  8. private intervalId = 0;
  9. componentDidMount() {
  10. this.addInterval();
  11. }
  12. componentDidUpdate(prevProps: Props) {
  13. const { interval } = this.props;
  14. if (interval !== prevProps.interval) {
  15. this.clearInterval();
  16. this.addInterval();
  17. }
  18. }
  19. componentWillUnmount() {
  20. this.clearInterval();
  21. }
  22. addInterval = () => {
  23. const { func, interval } = this.props;
  24. if (interval) {
  25. func().then(() => {
  26. if (interval) {
  27. this.intervalId = window.setTimeout(() => {
  28. this.addInterval();
  29. }, stringToMs(interval));
  30. }
  31. });
  32. }
  33. };
  34. clearInterval = () => {
  35. window.clearTimeout(this.intervalId);
  36. };
  37. render() {
  38. return null;
  39. }
  40. }