← Back to Blog

Creating a Roll Style Number Counter that Mimics a Slot Machine

coding
web

By Kevin Hou

2 minute read

I found a really cool way of making a number counter engaging. A co-worker at Salesforce, named Amy Lee, created a simple React component designed to mimic a slot machine. Instead of simply changing the number, the function "animates" the change and rolls up to that number. The cool thing about this is that it works for any number and it requires no CSS3 animation. It looks neat, especially with huge numbers!

Usage:

1<!-- The total time will be 300ms with one frame every 20ms. --> 2<AnimatedNumber number={this.state.number} time={300} frameRate={20}/> 3

Component source:

1const AnimatedNumber = React.createClass({ 2 getInitialState() { 3 return { 4 number: this.props.number 5 } 6 }, 7 componentWillReceiveProps(props) { 8 if (this.state.number !== props.number) { // If different number 9 if (this._interval) { //If theres an interval 10 clearInterval(this._interval) // Clear the existing interval 11 } 12 let framesLeft = this.props.time/this.props.frameRate; //Determine frame rate 13 let increment = (props.number - this.state.number)/(framesLeft + 1); //Determine increment per frame 14 this._interval = setInterval(() => { 15 if (framesLeft > 0) { //If there are frames 16 this.setState({ number: this.state.number + increment }); //Set new number 17 framesLeft--; //Subtract a frame 18 } else { //If done 19 clearInterval(this._interval); //Clear the interval 20 this._interval = null; //Set to null 21 this.setState({ number: props.number }); //Set the final value to the exact value just in case 22 } 23 }, this.props.frameRate); //How often it repeats 24 } 25 }, 26 render() { 27 return ( 28 <span> 29 {Math.round(this.state.number)} //Round if you don't want a decimal 30 </span> 31 ) 32 } 33}); 34