forked from facebook/react-native
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimerExample.js
More file actions
373 lines (332 loc) · 9.46 KB
/
TimerExample.js
File metadata and controls
373 lines (332 loc) · 9.46 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const RNTesterButton = require('../../components/RNTesterButton');
const React = require('react');
const performanceNow = require('fbjs/lib/performanceNow');
const {Alert, Platform, ToastAndroid, Text, View} = require('react-native');
function burnCPU(milliseconds) {
const start = performanceNow();
while (performanceNow() < start + milliseconds) {}
}
type RequestIdleCallbackTesterProps = $ReadOnly<{||}>;
type RequestIdleCallbackTesterState = {|message: string|};
class RequestIdleCallbackTester extends React.Component<
RequestIdleCallbackTesterProps,
RequestIdleCallbackTesterState,
> {
state = {
message: '-',
};
_idleTimer: ?IdleCallbackID = null;
_iters = 0;
componentWillUnmount() {
if (this._idleTimer != null) {
cancelIdleCallback(this._idleTimer);
this._idleTimer = null;
}
}
render() {
return (
<View>
<RNTesterButton onPress={this._run.bind(this, false)}>
Run requestIdleCallback
</RNTesterButton>
<RNTesterButton onPress={this._run.bind(this, true)}>
Burn CPU inside of requestIdleCallback
</RNTesterButton>
<RNTesterButton onPress={this._runWithTimeout}>
Run requestIdleCallback with timeout option
</RNTesterButton>
<RNTesterButton onPress={this._runBackground}>
Run background task
</RNTesterButton>
<RNTesterButton onPress={this._stopBackground}>
Stop background task
</RNTesterButton>
<Text>{this.state.message}</Text>
</View>
);
}
_run(shouldBurnCPU: boolean) {
if (this._idleTimer != null) {
cancelIdleCallback(this._idleTimer);
this._idleTimer = null;
}
this._idleTimer = requestIdleCallback(deadline => {
let message = '';
if (shouldBurnCPU) {
burnCPU(10);
message = 'Burned CPU for 10ms,';
}
this.setState({
message: `${message} ${deadline.timeRemaining()}ms remaining in frame`,
});
});
}
_runWithTimeout = () => {
if (this._idleTimer != null) {
cancelIdleCallback(this._idleTimer);
this._idleTimer = null;
}
this._idleTimer = requestIdleCallback(
deadline => {
this.setState({
message: `${deadline.timeRemaining()}ms remaining in frame, it did timeout: ${
deadline.didTimeout ? 'yes' : 'no'
}`,
});
},
{timeout: 100},
);
burnCPU(100);
};
_runBackground = () => {
if (this._idleTimer != null) {
cancelIdleCallback(this._idleTimer);
this._idleTimer = null;
}
const handler = deadline => {
while (deadline.timeRemaining() > 5) {
burnCPU(5);
this.setState({
message: `Burned CPU for 5ms ${this
._iters++} times, ${deadline.timeRemaining()}ms remaining in frame`,
});
}
this._idleTimer = requestIdleCallback(handler);
};
this._idleTimer = requestIdleCallback(handler);
};
_stopBackground = () => {
this._iters = 0;
if (this._idleTimer != null) {
cancelIdleCallback(this._idleTimer);
this._idleTimer = null;
}
};
}
type TimerTesterProps = $ReadOnly<{|
dt?: number,
type: string,
|}>;
class TimerTester extends React.Component<TimerTesterProps> {
_ii = 0;
_iters = 0;
_start = 0;
_timerId: ?TimeoutID = null;
_rafId: ?AnimationFrameID = null;
_intervalId: ?IntervalID = null;
_immediateId: ?Object = null;
_timerFn: ?() => any = null;
render() {
const args =
'fn' + (this.props.dt !== undefined ? ', ' + this.props.dt : '');
return (
<RNTesterButton onPress={this._run}>
Measure: {this.props.type}({args}) - {this._ii || 0}
</RNTesterButton>
);
}
componentWillUnmount() {
if (this._timerId != null) {
clearTimeout(this._timerId);
this._timerId = null;
}
if (this._rafId != null) {
cancelAnimationFrame(this._rafId);
this._rafId = null;
}
if (this._immediateId != null) {
clearImmediate(this._immediateId);
this._immediateId = null;
}
if (this._intervalId != null) {
clearInterval(this._intervalId);
this._intervalId = null;
}
}
_run = () => {
if (!this._start) {
const d = new Date();
this._start = d.getTime();
this._iters = 100;
this._ii = 0;
if (this.props.type === 'setTimeout') {
if (this.props.dt !== undefined && this.props.dt < 1) {
this._iters = 5000;
} else if (this.props.dt !== undefined && this.props.dt > 20) {
this._iters = 10;
}
this._timerFn = () => {
this._timerId = setTimeout(this._run, this.props.dt);
};
} else if (this.props.type === 'requestAnimationFrame') {
this._timerFn = () => {
this._rafId = requestAnimationFrame(this._run);
};
} else if (this.props.type === 'setImmediate') {
this._iters = 5000;
this._timerFn = () => {
this._immediateId = setImmediate(this._run);
};
} else if (this.props.type === 'setInterval') {
this._iters = 30; // Only used for forceUpdate periodicity
this._timerFn = null;
this._intervalId = setInterval(this._run, this.props.dt);
}
}
if (this._ii >= this._iters && this._intervalId == null) {
const d = new Date();
const e = d.getTime() - this._start;
const msg =
'Finished ' +
this._ii +
' ' +
this.props.type +
' calls.\n' +
'Elapsed time: ' +
e +
' ms\n' +
e / this._ii +
' ms / iter';
console.log(msg);
if (Platform.OS === 'ios') {
Alert.alert(msg);
} else if (Platform.OS === 'android') {
ToastAndroid.show(msg, ToastAndroid.SHORT);
}
this._start = 0;
this.forceUpdate(() => {
this._ii = 0;
});
return;
}
this._ii++;
// Only re-render occasionally so we don't slow down timers.
if (this._ii % (this._iters / 5) === 0) {
this.forceUpdate();
}
if (this._timerFn) {
this._timerId = this._timerFn();
}
};
clear = () => {
if (this._intervalId != null) {
clearInterval(this._intervalId);
// Configure things so we can do a final run to update UI and reset state.
this._intervalId = null;
this._iters = this._ii;
this._run();
}
};
}
exports.framework = 'React';
exports.title = 'Timers';
exports.description = 'A demonstration of Timers in React Native.';
exports.examples = [
{
title: 'this.setTimeout(fn, t)',
description: ('Execute function fn t milliseconds in the future. If ' +
't === 0, it will be enqueued immediately in the next event loop. ' +
'Larger values will fire on the closest frame.': string),
render: function(): React.Node {
return (
<View>
<TimerTester type="setTimeout" dt={0} />
<TimerTester type="setTimeout" dt={1} />
<TimerTester type="setTimeout" dt={100} />
</View>
);
},
},
{
title: 'this.requestAnimationFrame(fn)',
description: 'Execute function fn on the next frame.',
render: function(): React.Node {
return (
<View>
<TimerTester type="requestAnimationFrame" />
</View>
);
},
},
{
title: 'this.requestIdleCallback(fn)',
description: 'Execute function fn on the next JS frame that has idle time',
render: function(): React.Node {
return (
<View>
<RequestIdleCallbackTester />
</View>
);
},
},
{
title: 'this.setImmediate(fn)',
description: 'Execute function fn at the end of the current JS event loop.',
render: function(): React.Node {
return (
<View>
<TimerTester type="setImmediate" />
</View>
);
},
},
{
title: 'this.setInterval(fn, t)',
description: ('Execute function fn every t milliseconds until cancelled ' +
'or component is unmounted.': string),
render: function(): React.Node {
type IntervalExampleProps = $ReadOnly<{||}>;
type IntervalExampleState = {|
showTimer: boolean,
|};
class IntervalExample extends React.Component<
IntervalExampleProps,
IntervalExampleState,
> {
state = {
showTimer: true,
};
_timerTester: ?React.ElementRef<typeof TimerTester>;
render() {
return (
<View>
{this.state.showTimer && this._renderTimer()}
<RNTesterButton onPress={this._toggleTimer}>
{this.state.showTimer ? 'Unmount timer' : 'Mount new timer'}
</RNTesterButton>
</View>
);
}
_renderTimer = () => {
return (
<View>
<TimerTester
ref={ref => (this._timerTester = ref)}
dt={25}
type="setInterval"
/>
<RNTesterButton
onPress={() => this._timerTester && this._timerTester.clear()}>
Clear interval
</RNTesterButton>
</View>
);
};
_toggleTimer = () => {
this.setState({showTimer: !this.state.showTimer});
};
}
return <IntervalExample />;
},
},
];