I build a React Native Countdown Timer - javascript

I am facing a problem when the app is running the timer is working correctly however when I reset the timer the countdown timer is stuck in the initial state.
const [timer, setTimer] = useState(30)
useEffect(() => {
let interval = setInterval(() => {
setTimer(prev => {
if (prev === 1) clearInterval(interval)
return prev - 1
})
}, 1000)
newQuestion()
return () => clearInterval(interval)
}, [])
const handleReset = () => {
setTimer(30)
setScore(0)
}

Related

clearInterval() fails to stop an interval running on a timer [duplicate]

This question already has answers here:
clearInterval not working in React Application using functional component
(5 answers)
Closed 12 days ago.
First time using clearInterval() looking at other examples and the interval docs this appears to be the way to stop an interval. Not sure what I am missing.
The intention is to kill the timer when the currentStop prop updates.
import React, { useEffect, useState } from 'react';
type Props = {
stopNumber: number;
currentStop: number;
};
const timerComponent = ({ stopNumber, currentStop }: Props) => {
let interval: NodeJS.Timer;
// Update elapsed on a timer
useEffect(() => {
if (stopNumber === currentStop) {
interval = setInterval(() => {
console.log('timer is running');
}, 3000);
// Clear interval on unmount
return () => clearInterval(interval);
}
}, []);
// Clear timers that were running
useEffect(() => {
if (stopNumber !== currentStop) {
clearInterval(interval);
}
}, [currentStop]);
};
Store the intervalId on a ref instead
const timerComponent = ({ stopNumber, currentStop }: Props) => {
const intervalRef = useRef({
intervalId: 0
})
// Update elapsed on a timer
useEffect(() => {
if (stopNumber === currentStop) {
intervalRef.current.intervalId = setInterval(() => {
console.log('timer is running');
}, 3000);
// Clear interval on unmount
return () => clearInterval(intervalRef.current.intervalId);
}
}, []);
// Clear timers that were running
useEffect(() => {
if (stopNumber !== currentStop) {
clearInterval(intervalRef.current.intervalId);
}
}, [currentStop]);
};
Use a ref to store the interval id instead.
let interval = useRef();
// to start the setInterval:
interval.current = setInterval(...);
// to stop the setInterval:
clearInterval(interval.current);

clearInterval() doesn't clear interval in React

I want to increment the number of users after each 200ms till 5000 with the below code. But it doesn't clear the interval when the number of users greater than 5000.
const Cards = () => {
const [users, setUsers] = useState(40);
useEffect(() => {
const setIntervalUsers = setInterval(() => {
setUsers((prevUsers) => prevUsers = prevUsers + 100)
}, 200);
if (users >= 5000) {
console.log('ok');
clearInterval(setIntervalUsers)
}
}, []);
return (<div>number of users {users} </div>)}
I would suggest you to return a clean up function so you don't register the interval twice in case you are in StrictMode with React 18, and also to remove it from the memory when the component gets unmounted.
Also use a ref set with useRef and a separate useEffect that would watch changes in users and clear the interval there. Like so:
import { useEffect, useRef, useState } from "react";
const Cards = () => {
const [users, setUsers] = useState(40);
const intervalRef = useRef();
useEffect(() => {
if (users >= 5000) {
console.log("ok");
clearInterval(intervalRef.current);
}
}, [users]);
useEffect(() => {
intervalRef.current = setInterval(() => {
setUsers((prevUsers) => (prevUsers = prevUsers + 100));
}, 200);
return () => clearInterval(intervalRef.current);
}, []);
return <div>number of users {users} </div>;
};
This doesnt work because:
you never call the useEffect again to check if the condition is met
the interval ref is lost
I made a working sample of your code here : https://codepen.io/aSH-uncover/pen/wvmYdNy
Addintionnaly you should clean the interval when the component is destroyed by returning the cleanInterval call in the hook that created the inteerval
const Card = ({ step }) => {
const intervals = useRef({})
const [users, setUsers] = useState(40)
useEffect(() => {
intervals.users = setInterval(() => {
setUsers((prevUsers) => prevUsers = prevUsers + step)
}, 200)
return () => clearInterval(intervals.users)
}, [])
useEffect(() => {
if (users >= 5000) {
clearInterval(intervals.users)
}
}, [users])
return (<div>number of users {users} </div>)
}
I came up with this. You can try it out. Although there are many ways suggested above
const [users, setUsers] = useState(40);
const [max_user, setMaxUser] = useState(true);
let setIntervalUsers: any;
let sprevUsers = 0;
useEffect(() => {
if (max_user) {
setIntervalUsers = setInterval(() => {
sprevUsers += 100;
if (sprevUsers >= 5000) {
setMaxUser(false);
clearInterval(setIntervalUsers);
} else {
setUsers(sprevUsers);
}
}, 200);
}
}, []);
The way how you check for your condition users >= 5000 is not working because users is not listed as a dependency in your useEffect hook. Therefore the hook only runs once but doesnt run again when users change. Because of that you only check for 40 >= 5000 once at the beginning.
An easier way to handle that is without a setInterval way.
export const Cards = () => {
const [users, setUsers] = useState(40);
useEffect(() => {
// your break condition
if (users >= 5000) return;
const increment = async () => {
// your interval
await new Promise((resolve) => setTimeout(resolve, 200));
setUsers((prevState) => prevState + 100);
}
// call your callback
increment();
// make the function run when users change.
}, [users]);
return <p>current number of users {users}</p>
}

React: ClearInterval and Immediately Start Again

I have a component that sets off a timer which updates and makes an axios request every 30 seconds. It uses a useRef which is set to update every 30 seconds as soon as a function handleStart is fired.
const countRef = useRef(null);
const lastUpdatedRef = useRef(null);
const [lastUpdated, setLastUpdated] = useState(Date.now())
const handleStart = () => {
countRef.current = setInterval(() => {
setTimer((timer) => timer + 1);
}, 1000);
lastUpdatedRef.current = setInterval(() => {
setLastUpdated(Date.now());
}, 30000);
};
Now I have a useEffect that runs a calculate function every 30 seconds whenever lastUpdated is triggered as a dependency:
const firstCalculate = useRef(true);
useEffect(() => {
if (firstCalculate.current) {
firstCalculate.current = false;
return;
}
console.log("calculating");
calculateModel();
}, [lastUpdated]);
This updates the calculate function every 30 seconds (00:30, 01:00, 01:30 etc.) as per lastUpdatedRef. However, I want the timer to restart from when lastUpdated state has been modified elsewhere (e.g. if lastUpdated was modified at 00:08, the next updated will be 00:38, 01:08, 01:38 etc.). Is there a way to do this?
Basically it sounds like you just need another handler to clear and restart the 30 second interval updating the lastUpdated state.
Example:
const handleOther = () => {
clearInterval(lastUpdatedRef.current);
lastUpdatedRef.current = setInterval(() => {
setLastUpdated(Date.now());
}, 30000);
}
Full example:
const calculateModel = () => console.log("calculateModel");
export default function App() {
const countRef = React.useRef(null);
const lastUpdatedRef = React.useRef(null);
const [lastUpdated, setLastUpdated] = React.useState(Date.now());
const [timer, setTimer] = React.useState(0);
const handleStart = () => {
countRef.current = setInterval(() => {
setTimer((timer) => timer + 1);
}, 1000);
lastUpdatedRef.current = setInterval(() => {
setLastUpdated(Date.now());
}, 30000);
};
const handleOther = () => {
clearInterval(lastUpdatedRef.current);
lastUpdatedRef.current = setInterval(() => {
setLastUpdated(Date.now());
}, 30000);
};
const firstCalculate = React.useRef(true);
React.useEffect(() => {
if (firstCalculate.current) {
firstCalculate.current = false;
return;
}
console.log("calculating");
calculateModel();
}, [lastUpdated]);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<div>Timer: {timer}</div>
<button type="button" onClick={handleStart}>
Start
</button>
<button type="button" onClick={handleOther}>
Other
</button>
</div>
);
}
Don't forget to clear any running intervals when the component unmounts!
React.useEffect(() => {
return () => {
clearInterval(countRef.current);
clearInterval(lastUpdatedRef.current);
};
}, []);

React Hooks Clock - Clear SetInterval After Certain Time

I have a stopwatch function in React that I would like to stop after 15 minutes. I am not sure how to use clearInterval() in this case:
const [timer, setTimer] = useState(0);
const [isActive, setIsActive] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const countRef = useRef(null);
const lastUpdatedRef = useRef(null);
const [minutes,setMinutes] = useState(0)
const [seconds,setSeconds] = useState(0)
const timeCeiling = 900; //maximum minutes is 15
const timeFloor = 60; //maximum seconds is 60 so it resets after
useEffect(() => {
if (timer < timeCeiling) {
setMinutes(Math.floor(timer / 60));
setSeconds(timer % 60);
} else {
setMinutes(15);
setSeconds(0);
}
}, [timer]);
const handleStart = () => {
setIsActive(true);
setIsPaused(true);
countRef.current = setInterval(() => {
setTimer((timer) => timer + 1);
}, 1000);
lastUpdatedRef.current = setInterval(() => {
setLastUpdated(Date.now());
}, 30000);
};
The user clicks on the handleStart function which triggers a useEffect. It also has a lastUpdated dependency which triggers another function every 30 seconds.
The clock should end after 15:00 but it still continues after- where should I put clearInterval so that it stops the clock after 15 minutes? Or is there another way to do this?
I would place it in the useEffect that is running each time timer updates. Clear the interval in the else branch when the limit it hit.
useEffect(() => {
if (timer < timeCeiling) {
setMinutes(Math.floor(timer / 60));
setSeconds(timer % 60);
} else {
clearInterval(countRef.current);
setMinutes(15);
setSeconds(0);
}
}, [timer]);
You might also want to add an additional useEffect hook to clear any running timers should the component unmount before you manually clear them.
useEffect(() => {
return () => {
clearInterval(countRef.current);
clearInterval(lastUpdatedRef.current);
};
}, []);
You can add cleare interval in the else condition:
useEffect(() => {
if (timer < timeCeiling) {
setMinutes(Math.floor(timer / 60));
setSeconds(timer % 60);
} else {
setMinutes(15);
setSeconds(0);
countRef.current && clearInterval(countRef.current);
lastUpdatedRef.current && clearInterval(lastUpdatedRef.current);
}
}, [timer]);
And you should cleare interval when component un-mount:
useEffect(() => {
return () => {
countRef.current && clearInterval(countRef.current);
};
}, [countRef]);
useEffect(() => {
return () => {
lastUpdatedRef.current && clearInterval(lastUpdatedRef.current);
};
}, [lastUpdatedRef]);
I think you should use clearInterval in the else block in useEffect. Maybe this way:
else {
setMinutes(15);
setSeconds(0);
clearInterval(countRef.current) // I hope this works
}

React Native: Timer keeps reseting

I am trying to do a countdown timer but after it gets to 1 it resets to 5 when its supposed to go to '00:00', I don't know where I am going wrong please may someone help me
This is my code:
const CountDown = () => {
const RESET_INTERVAL_S = 5;
const formatTime = (time) =>
`${String(Math.floor(time / 60)).padStart(2, "0")}:${String(
time % 60
).padStart(2, "0")}`;
const Timer = ({ time }) => {
const timeRemain = RESET_INTERVAL_S - (time % RESET_INTERVAL_S);
return (
<>
<Text>{formatTime(timeRemain)}</Text>
</>
);
};
const IntervalTimerFunctional = () => {
const [time, setTime] = useState(0);
console.log("The time is", time);
useEffect(() => {
const timerId = setInterval(() => {
setTime((t) => t + 1);
}, 1000);
return () => clearInterval(timerId);
}, []);
return <Timer time={time} />;
};
return <IntervalTimerFunctional />;
};
I am not sure this is a perfect solution but this could work:
You could stop your timer when it reaches its maximum value:
useEffect(() => {
const timerId = setInterval(() => {
setTime((t) => {
if(t + 1 === RESET_INTERVAL_S) {
clearInterval(timerId)
}
return t + 1;
});
}, 1000);
return () => clearInterval(timerId);
}, []);
And display "00:00" when you have reached the limit:
<Text>{time === RESET_INTERVAL_S ? "00:00" : formatTime(timeRemain)}</Text>
Here is a working example
useEffect(() => {
const timerId = setInterval(() => {
setTime((t) => t + 1);
}, 1000);
return () => clearInterval(timerId);
}, []);
You need to set the value you want to repeat on. If not, this will keep resetting it.
You could also add a condition to check the value of the timer and stop it. like this:
{
time !== 0 ? setTime((t) => t+1): time = 0;
}
Here is a similar problem to yours.

Categories