CM3050 Lab 4704: Stopwatch
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import {useState, useRef} from 'react';
export default function App() {
const [playState, setPlayState] = useState(false);
const [timerValue, setTimerValue] = useState("00:00:00")
const interval = useRef(undefined);
const toggleState = () => {
if(!playState) {
setPlayState(!playState);
secs = 0;
interval.current = setInterval(() => {
secs++;
time_string = new Date(secs * 1000).toISOString();
display_text = time_string.substr(11, 8);
setTimerValue(display_text)
}, 1000)
} else {
setPlayState(!playState);
clearInterval(interval.current)
interval.current = undefined;
setTimerValue("00:00:00")
}
}
return (
<View style={[styles.container]}>
<Text style={styles.timeDisplay}>{timerValue}</Text>
<TouchableOpacity
style={[styles.button, playState ? styles.stopButton : styles.startButton]}
onPress={toggleState}
>
<Text
style={[styles.buttonText, playState ? styles.stopText : styles.startText]}
>
{playState ? "STOP" : "START"}
</Text>
</TouchableOpacity>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#000",
alignItems: 'center',
justifyContent: 'center',
},
timeDisplay: {
fontSize: 80,
fontWeight: "bold",
color: "white",
marginBottom: 50
},
button: {
width: "80%",
height: 80,
borderRadius: 50,
margin: 10,
justifyContent: "center",
},
startButton: {
backgroundColor: "#fff"
},
stopButton: {
backgroundColor: "#000",
borderWidth: 7,
borderColor: "red"
},
buttonText: {
fontSize: 30,
fontWeight: "bold",
width: "100%",
textAlign: "center"
},
startText: {
color: "black",
},
stopText: {
color: "red"
}
});