UNPKG

react-on-time

Version:
68 lines (67 loc) 2.35 kB
var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); import * as React from 'react'; import * as PropTypes from 'prop-types'; var Interval = (function (_super) { __extends(Interval, _super); function Interval() { var _this = _super !== null && _super.apply(this, arguments) || this; _this.state = { tick: 0 }; return _this; } Interval.prototype.componentDidMount = function () { this.start(); }; Interval.prototype.componentDidUpdate = function (prevProps) { if (prevProps.delay !== this.props.delay || prevProps.pause !== this.props.pause) { this.stop(); this.start(); } }; Interval.prototype.componentWillUnmount = function () { this.stop(); }; Interval.prototype.start = function () { var _this = this; if (!this.props.pause) { this.timeout = window.setInterval(function () { _this.setState(function (_a) { var tick = _a.tick; return ({ tick: tick + 1 }); }, function () { _this.props.onTick && _this.props.onTick(_this.state.tick); }); }, this.props.delay || 1000); this.props.onTick && this.props.onTick(this.state.tick); } }; Interval.prototype.stop = function () { if (this.timeout) { window.clearInterval(this.timeout); this.timeout = 0; } }; Interval.prototype.render = function () { return this.props.children ? this.props.children(this.state.tick) : null; }; Interval.propTypes = { delay: PropTypes.number.isRequired, pause: PropTypes.bool, onTick: PropTypes.func, children: PropTypes.func }; return Interval; }(React.Component)); export { Interval };