Skip to content

Instantly share code, notes, and snippets.

@andersonssantana
Last active September 13, 2022 17:14
Show Gist options
  • Save andersonssantana/34e17bc6a950bb609db90785d5bb0029 to your computer and use it in GitHub Desktop.
Save andersonssantana/34e17bc6a950bb609db90785d5bb0029 to your computer and use it in GitHub Desktop.
Simple countdown timer for React.js
import React, { Component } from 'react';
class CountdownTimer extends Component {
state = {
time: 30
}
componentDidMount() {
this.startTimer();
}
componentWillUnmount() {
this.stopTimer();
}
startTimer = () => {
clearInterval(this.interval);
this.setState({ time: 30 })
this.interval = setInterval(() => {
const { time } = this.state;
if (time > 0) {
this.setState({ time: time - 1 })
} else {
this.stopTimer();
}
}, 1000)
}
stopTimer = () => {
const { time } = this.state;
console.log(`Você parou em ${time} segundos`)
clearInterval(this.interval);
}
render() {
const { time } = this.state;
return (
<div>
<span>
{ `Tempo restante: ${time} segundos` }
</span>
<div>
<button type='button' onClick={ this.startTimer }>
Iniciar Timer
</button>
</div>
<div>
<button type='button' onClick={ this.stopTimer }>
Parar Timer
</button>
</div>
</div>
);
}
}
export default CountdownTimer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment