'React native custom timer works 10 times slower
UPD: Problem is solved. I just swapped setInterval to 1 sec instead of 1 ms. but i have no idea why it's not working with ms, if it's all mathematically allright. Thanks to commentators
There's my custom countdown Timer component (not ready). I have some problems with seconds counting. I've tried different ways to calculate seconds. Somewhy it's always works wrong.
class Timer extends Component{
state = {
playerTime : 3*60*1000, //initialize time with 3 minutes
hours : ()=> {
//did not tryed wait more than hour, but first countdown is well
var hours = hours = Math.floor((this.state.playerTime/(1000*60*60))%24);
return hours;
},
minutes : () => {
//minutes do countdown well
var minutes = Math.floor((this.state.playerTime/(1000*60))%60);
return minutes;
},
seconds : () => {
// if divide by 100 seconds starts from 59, but after 0 goes 59 again, minutes do not countdown
//if divide by 1000 its works in right way but in 10 times slower
var seconds = Math.floor((this.state.playerTime/1000)%60);
return seconds;
},
};
render(){
return(
//create a button with black backround
<TouchableOpacity style={styles.playerButton}
onPress={() => { //start countdowning timer
setInterval(() => {
this.setState({playerTime : Number(this.state.playerTime-1)})
} , 1)
}}>
<View justifyContent="center">
<Text style={styles.timerText}>
{/*output a time in text format h:m:s */}
{this.state.hours()}:
{this.state.minutes()}:
{this.state.seconds()}
</Text>
</View>
</TouchableOpacity>
);
};
};
I'm new in JS and React Native. Developing my own chess clock. Tell me please if you know some open-source js chess clocks
Solution 1:[1]
First you should probably use function components, it's the right things to do for 99% of the use cases.
Also, hours, minutes and seconds should not be part of your state because you don't act on them directly. These are values that you are able to derive from the only state you need (playerTime).
Here is a working example (you will have to study the code a bit to see how it works and adapt for your case if you really want to use a class component
import React, { useState } from "react";
export const Timer = ({ initialTime }) => {
const [time, setTime] = useState(initialTime);
const start = () => {
setInterval(() => setTime((time) => time - 1), 1000);
};
const hours = Math.floor(time / 3600);
const minutes = Math.floor((time - hours * 3600) / 60);
const seconds = time - minutes * 60;
return (
<>
<button type="button" onClick={start}>
Start countdown
</button>
<div>
<h2>{time}</h2>
{hours}:{minutes}:{seconds}
</div>
</>
);
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | soueuls |
