So I am working on a count down timer for every seconds, and if it is less then 60 seconds, count down every 10ms.
I have tried many ways there is always a delay. E.g. the displayed counter down is slower than the actual count down.
Here is what I am doing – I store a endTime
UTC in database (backend), then use websocket to publish the data to the front end, then front end start the count down by comparing the endTime
and current time UTC, and the loop is done by requestAnimationFrame
. Even with all this, the count down on screen is off by a second for every minutes. BTW, the front end is react
.
Here is the code:
useEffect(() => {
if (!isRunning || timeLeft === null || timeLeft <= 0) return;
const startTime = performance.now();
const totalDuration = timeLeft * 1000;
const updateTimer = () => {
const elapsedTime = performance.now() - startTime;
const remainingTime = Math.max(0, totalDuration - elapsedTime) / 1000;
setTimeLeft(remainingTime);
if (remainingTime <= 0) {
setIsRunning(false);
return;
}
timeoutRef.current = requestAnimationFrame(updateTimer);
};
timeoutRef.current = requestAnimationFrame(updateTimer);
return () => {
if (timeoutRef.current !== null) {
cancelAnimationFrame(timeoutRef.current);
timeoutRef.current = null;
}
};
}, [isRunning, timeLeft, clientId]);
Any suggestions?