diff --git a/src/WhenIdle/index.ts b/src/WhenIdle/index.ts new file mode 100644 index 00000000..515bd025 --- /dev/null +++ b/src/WhenIdle/index.ts @@ -0,0 +1,39 @@ +import {Component} from 'react'; + +const RIC = (window as any).requestIdleCallback || ((fn, {timeout = 35} = {}) => setTimeout(fn, 35)); + +export interface IWhenIdleProps { + timeout?: number; +} + +export interface IWhenIdleState { + ready: boolean; +} + +export class WhenIdle extends Component { + mounted = false; + + state: IWhenIdleState = { + ready: false + }; + + componentDidMount () { + this.mounted = true; + + const {timeout} = this.props; + + RIC(() => { + if (this.mounted) { + this.setState({ready: true}); + } + }, {timeout}); + } + + componentWillUnmount () { + this.mounted = false; + } + + render () { + return this.state.ready ? this.props.children : null; + } +}