Skip to content

Instantly share code, notes, and snippets.

@evanrs
Created February 26, 2016 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evanrs/7a97ecb31bb8f187b4a9 to your computer and use it in GitHub Desktop.
Save evanrs/7a97ecb31bb8f187b4a9 to your computer and use it in GitHub Desktop.
Poll at interval or on window focus, throttle between interval and focus events.
import React, { Component, PropTypes } from 'react'
import throttle from 'lodash/throttle';
import attempt from 'lodash/attempt';
class Poll extends Component {
static propTypes = {
throttle: PropTypes.number,
interval: PropTypes.number,
onFocus: PropTypes.func,
onInterval: PropTypes.func
};
static defaultProps = {
interval: 60000,
throttle: 30000
};
throttle =
throttle(attempt, this.props.throttle, { trailing: false });
componentDidMount() {
this.mount(this.props);
}
componentWillReceiveProps(props) {
if (props.onInterval !== this.props.onInterval ||
props.onFocus !== this.props.onFocus) {
this.unmount();
this.mount(props);
}
}
componentWillUnmount () {
this.unmounting = true;
this.unmount();
}
mount(props) {
let { interval, onFocus, onInterval } = props;
if (onFocus) {
this.onFocus = this.throttle.bind(this, onFocus);
global.addEventListener('focus', this.onFocus);
}
if (onInterval) {
this.onInterval = this.throttle.bind(this, onInterval);
this.interval = global.setInterval(this.onInterval, interval);
}
}
unmount() {
this.throttle.cancel();
this.onFocus &&
global.removeEventListener('focus', this.onFocus);
this.interval &&
global.clearInterval(this.interval);
}
render () {
return this.props.children
}
}
export default Poll;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment