-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
71 lines (62 loc) · 1.48 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* External dependencies
*/
import { without } from 'lodash';
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';
/**
* Internal dependencies
*/
import createHigherOrderComponent from '../create-higher-order-component';
/**
* Browser dependencies
*/
const { clearTimeout, setTimeout } = window;
/**
* A higher-order component used to provide and manage delayed function calls
* that ought to be bound to a component's lifecycle.
*
* @param {Component} OriginalComponent Component requiring setTimeout
*
* @return {Component} Wrapped component.
*/
const withSafeTimeout = createHigherOrderComponent(
( OriginalComponent ) => {
return class WrappedComponent extends Component {
constructor() {
super( ...arguments );
this.timeouts = [];
this.setTimeout = this.setTimeout.bind( this );
this.clearTimeout = this.clearTimeout.bind( this );
}
componentWillUnmount() {
this.timeouts.forEach( clearTimeout );
}
setTimeout( fn, delay ) {
const id = setTimeout( () => {
fn();
this.clearTimeout( id );
}, delay );
this.timeouts.push( id );
return id;
}
clearTimeout( id ) {
clearTimeout( id );
this.timeouts = without( this.timeouts, id );
}
render() {
return (
<OriginalComponent
{ ...this.props }
setTimeout={ this.setTimeout }
clearTimeout={ this.clearTimeout }
/>
);
}
};
},
'withSafeTimeout'
);
export default withSafeTimeout;