-
Notifications
You must be signed in to change notification settings - Fork 0
/
react.looper.jsx
87 lines (70 loc) · 2.37 KB
/
react.looper.jsx
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import React, {Component} from 'react';
import {looper} from "promise-timeout-and-looper";
/**
* this example file is meant to show how the looper helper works.
*/
export default class Looper extends Component {
state = {
looper: null,
numbers: [],
debug: false,
};
componentDidMount() {
// initialize the looper
this.setState({looper: looper});
}
componentWillUnmount() {
// Make sure the looper is canceled
this.loopCancel();
}
loopStart = async () => {
await this.setState({numbers: [1]});
let max_run = 10;
// tell this function to wait until the looping is done
await this.state.looper.loopStart({
// outputs debug information to the console
debug: this.state.debug,
// timeout in milliseconds between ticks
ms: 500,
// executes after the timeout
loop_tick_callback: async () => {
if (--max_run < 1) {
// this return false cancels the looper automatically
return false;
}
const {
numbers: {
[this.state.numbers.length - 1]: last_number = 0
},
} = this.state;
const numbers = this.state.numbers;
numbers.push(last_number + 1);
await this.setState({numbers});
},
});
const numbers = this.state.numbers;
numbers.push('Done looping');
await this.setState({numbers});
};
loopCancel = () => {
this.state.looper && this.state.looper.loopCancel({debug: true});
};
render() {
return (
<div>
<div className="btn-group">
<button className="btn btn-primary marginB5" onClick={this.loopStart}>
Start looping
</button>
<button className="btn btn-warning marginB5" onClick={this.loopCancel}>
Stop looping
</button>
</div>
<ul className="marginT10">
{this.state.numbers.length > 0 ? <li>Starting</li> : null}
{this.state.numbers.map(n => <li>{n}</li>)}
</ul>
</div>
)
}
}