I have a basic timer in React that implements setInterval()
. I've read that this can be a bit problematic with lag and I have found it to be so- whenever I go to a different tab on Chrome for a prolongued period of time, it definitely starts to lag. I would like to implement a basic web worker in JavaScript to improve my timer, but not sure how to do it. Here is how my clock is powered:
const [timer, setTimer] = useState(0);
const [isActive, setIsActive] = useState(false);
const [isPaused, setIsPaused] = useState(false);
const countRef = useRef(null);
const [minutes,setMinutes] = useState(0);
const [seconds,setSeconds]= useState(0);
const timeCeiling = 7800; //clock goes up to 130 minutes
const timeFloor = 60;
useEffect(() => {
setMinutes(Math.floor(timer / 60));
setSeconds(timer % 60);
}, [timer]);
//Start Timer
const handleStart = () => {
countRef.current = setInterval(() => {
setTimer((timer) => timer + 1);
}, 1000);
};
//Pause Timer
const handlePause = () => {
clearInterval(countRef.current);
setIsPaused(false);
};
//Resume Timer
const handleResume = () => {
setIsPaused(true);
countRef.current = setInterval(() => {
setTimer((timer) => timer + 1);
}, 1000);
};
//Reset Timer
const handleReset = () => {
clearInterval(countRef.current);
setIsActive(false);
setIsPaused(false);
setTimer(0)
};
//And now here are the functions to increment and decrement minutes and seconds:
const increaseMinutes = () => {
timer >= timeCeiling ? checkMaximumTime() : setTimer((timer) => timer + 60);
};
const decreaseMinutes = () => {
timer < timeFloor ? checkMinimumTime() : setTimer((timer) => timer - 60);
};
const increaseSeconds = () => {
setTimer((timer) => timer + 1);
};
const decreaseSeconds = () => {
timer === 0 ? checkMinimumTime() : setTimer((timer) => timer - 1);
};
const checkMinimumTime = () => {
alert("Can't go lower than zero minutes!");
return;
};
const checkMaximumTime = () => {
alert("Maximum minutes reached");
return;
};
All the functions implement onClick
buttons in the JSX. I wanted to know how I can implement web workers to eliminate the lag when browsing other tabs, or any other solution.