Countdown timer in React
You have to setState
every second with the seconds remaining (every time the interval is called). Here's an example:
class Example extends React.Component { constructor() { super(); this.state = { time: {}, seconds: 5 }; this.timer = 0; this.startTimer = this.startTimer.bind(this); this.countDown = this.countDown.bind(this); }
secondsToTime(secs){ let hours = Math.floor(secs / (60 * 60));
let divisor_for_minutes = secs % (60 * 60); let minutes = Math.floor(divisor_for_minutes / 60);
let divisor_for_seconds = divisor_for_minutes % 60; let seconds = Math.ceil(divisor_for_seconds);
let obj = { "h": hours, "m": minutes, "s": seconds }; return obj; }
componentDidMount() { let timeLeftVar = this.secondsToTime(this.state.seconds); this.setState({ time: timeLeftVar }); }
startTimer() { if (this.timer == 0 && this.state.seconds > 0) { this.timer = setInterval(this.countDown, 1000); } }
countDown() { // Remove one second, set state so a re-render happens. let seconds = this.state.seconds - 1; this.setState({ time: this.secondsToTime(seconds), seconds: seconds, }); // Check if we're at zero. if (seconds == 0) { clearInterval(this.timer); } }
render() { return( <div> <button onClick={this.startTimer}>Start</button> m: {this.state.time.m} s: {this.state.time.s} </div> ); }}
ReactDOM.render(<Example/>, document.getElementById('View'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><div id="View"></div>
How should i pass props, I use countdown timer reactjs package
As per the document, onComplete()
should be as follows:
<CountdownCircleTimer
isPlaying
duration={30}
colors={["#FFAD22", "#714DFF", "#5AD4FB", "#A30000"]}
colorsTime={[25, 20, 15, 0]}
onComplete={() => {
// your api call
return { shouldRepeat: true, delay: 0 };
}}
>
Related Topics
How to Sum the Values of a JavaScript Object
Detect If an Element Is Visible with Jquery
Access Non-Numeric Object Properties by Index
Difference Between Obtrusive and Unobtrusive JavaScript
Javascript: Uploading a File... Without a File
Keep Bootstrap Dropdown Open When Clicked Off
Why Do I Need to Await an Async Function When It Is Not Supposedly Returning a Promise
Pass Parameter with Python Flask in External JavaScript
Getting a Union of Two Arrays in JavaScript
JSON Transfer of Bigint: 12000000000002539 Is Converted to 12000000000002540
Waiting for Image to Load in JavaScript
JavaScript Call Nested Function
React Doesn't Reload Component Data on Route Param Change or Query Change