I made this simple React program. Can someone tell me why the stop button doesn’t work? Shouldn’t the boolean statement stop it from repeating after I click the stop button?
import "./styles.css";
import { useState, useEffect } from "react";
import { Text, TextInput, View, Image, Button } from "react-native";
export default function App() {
const [time, setTime] = useState(0);
const [stopped, setStopped] = useState(false);
function start() {
if (stopped == false) {
setTimeout(() => {
setTime((time) => time + 1);
start();
}, 1000);
}
}
return (
<View>
<Text>{time}</Text>
<Button onPress={start} title="Start Timer" />
<Button onPress={() => setStopped(true)} title="Stop Timer" />
</View>
);
}
2
Answers
The reason the "Stop Timer" button doesn’t work as expected is due to how the setTimeout function works. Even when you set stopped to true, the existing timeout function that was triggered before will still execute. This is because the setTimeout function schedules a single execution of the provided function after a specified delay, and changing the stopped value will not cancel or interrupt the ongoing timeout.
To achieve the behavior you want, you can use the clearTimeout function to cancel the ongoing timeout when the "Stop Timer" button is pressed
Edit: Also add a useEffect to clean up the timeout when the component unmounts.
In React Native, you can use the setTimeout and clearTimeout functions to start and stop a timeout respectively when a button is clicked. Here’s how you can do it:
Set up a state variable to track the timeout status (active or inactive).
Create a function to start the timeout when the button is clicked.
Create another function to stop the timeout when the button is clicked again or another event occurs.
Here’s an example implementation: