Skip to content

Commit 3c60ddb

Browse files
committed
Switched from setInterval to requestAnimationFrame
1 parent 3fcfb2b commit 3c60ddb

1 file changed

Lines changed: 13 additions & 8 deletions

File tree

src/Spinner.js

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import TruncatingText from './TruncatingText.js';
66
const FRICTION = .0001;
77
const SPIN_MIN = 5;
88
const SPIN_MAX = 10;
9-
const FRAME_RATE = 100;
9+
//const FRAME_RATE = 100;
1010
const FONT_SIZE = 22;
1111

1212
class Spinner extends React.PureComponent {
@@ -23,7 +23,7 @@ class Spinner extends React.PureComponent {
2323
}
2424

2525
handleClick() {
26-
if(!this.timerID) {
26+
if(!this.animationID) {
2727
this.animationTime = 0;
2828
this.previousFrameTime = performance.now()
2929

@@ -40,16 +40,19 @@ class Spinner extends React.PureComponent {
4040

4141
console.log(this.props.items[i]);
4242

43+
/*
4344
this.timerID = setInterval(
4445
() => this.tick(initialV, initialSpin),
4546
1000/FRAME_RATE
4647
);
48+
*/
49+
this.animationID = window.requestAnimationFrame(() => this.tick(initialV, initialSpin));
4750
}
4851
}
4952

5053
componentWillUnmount() {
51-
if(this.timerID)
52-
clearInterval(this.timerID);
54+
if(this.animationID)
55+
window.cancelAnimationFrame(this.animationID);
5356
}
5457

5558
tick(initialV, initialSpin) {
@@ -61,9 +64,11 @@ class Spinner extends React.PureComponent {
6164
// this creates problems at high FRICTION values on the last frame
6265
// TODO: think of some way to avoid that, maybe special case for last frame here?
6366
if(velocity <= 0) {
64-
clearInterval(this.timerID);
65-
this.timerID = false;
67+
window.cancelAnimationFrame(this.animationID);
68+
this.animationID = false;
6669
}
70+
else
71+
window.requestAnimationFrame(() => this.tick(initialV, initialSpin));
6772

6873
this.setState({
6974
spinAngle: (initialSpin + initialV*this.animationTime - .5*FRICTION*this.animationTime*this.animationTime) % 360
@@ -95,7 +100,7 @@ class Spinner extends React.PureComponent {
95100
stroke="black"
96101
strokeWidth={1}
97102
perfectDrawEnabled={false}
98-
listening={!this.timerID}
103+
listening={!this.animationID}
99104
/>
100105
);
101106

@@ -125,7 +130,7 @@ class Spinner extends React.PureComponent {
125130
onClick={() => this.handleClick()}
126131
maxWidth={this.props.radius*.70} // TODO: base this off of the slice angle for smaller slices
127132
perfectDrawEnabled={false}
128-
listening={!this.timerID}
133+
listening={!this.animationID}
129134
/>
130135
);
131136
}

0 commit comments

Comments
 (0)