I am trying to create stopwatch application. I'm using setInterval function to increase time. But my app to stay behind windows clock app.
I launched both at same time.
App.js
export default function App() {
const [time, setTime] = useState({ running: false, time: 0 });
const [count, setCount] = useState(time.time);
useEffect(() => {
console.log(count);
let id;
if (time.running)
id = setInterval(() => setCount(count => count + 100), 100);
return () => {
if (time.running)
clearInterval(id);
};
}, [time.running]);
const counter = () => {
if (time.running) {
setTime({
running: false,
time: time.time
});
} else {
setTime({
running: true,
time: time.time
});
}
};
}
return (
<TimeContext.Provider value={{ time, setTime }}>
<SafeAreaView style={[styles.container, { backgroundColor: theme.background }]}>
<View style={styles.stopwatch}>
<Stopwatch time={count} />
</View>
</SafeAreaView>
</TimeContext.Provider>
);
Stopwatch.js
export default function Stopwatch({ time }) {
return (
<Text style={[styles.text, { color: theme.text }]}>{msToTime(time)}</Text>
);
}
ms-to-time.js
export default function msToTime(duration) {
var milliseconds = Math.floor((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
When click start button counter function triggers.
I'm increasing count variable instead of time.time cuz other components using time so i blocking render others this way.