React/NextJS useEffect Timer Incrementing Coins Every Nanosecond Instead of Every Second

I am developing a mining application using React where a timer should increment the user’s coins every second. However, the timer is adding coins at an incredibly fast rate (every nanosecond) instead of every second.

Here is the code I am using in my useEffect hook:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> const userDocRef = doc(db, 'users', user.id); // Adjust the path to your Firestore collection
await setDoc(userDocRef, data, { merge: true });
};
useEffect(() => {
const fetchUserState = async () => {
if (user && !user.anotherStart) {
toggleSpin();
const userDocRef = doc(db, 'users', user.id);
try {
const userDoc = await getDoc(userDocRef);
if (userDoc.exists()) {
const userData = userDoc.data();
setUser((prevUser) => ({
...prevUser,
...userData
}));
const elapsedTime = Math.floor((Date.now() - userData.startTime) / 1000);
const remainingTime = userData.countdown - elapsedTime;
// Start countdown if necessary
if (elapsedTime >= userData.countdown) {
await updateUserInFirestore({ isSpinning: false });
setCoins(user.countdown);
setShowClaimButton(true); // Show claim button if countdown is completed
setIsSpinning(false);
setTimer(null);
} else {
startCountdown(remainingTime);
}
}
} catch (error) {
console.error('Error fetching user state:', error);
}
}
};
// Perform initial fetch only once when user.isSpinning is true
if (user && user.isSpinning) {
fetchUserState();
}
}, [user, startCountdown]);
</code>
<code> const userDocRef = doc(db, 'users', user.id); // Adjust the path to your Firestore collection await setDoc(userDocRef, data, { merge: true }); }; useEffect(() => { const fetchUserState = async () => { if (user && !user.anotherStart) { toggleSpin(); const userDocRef = doc(db, 'users', user.id); try { const userDoc = await getDoc(userDocRef); if (userDoc.exists()) { const userData = userDoc.data(); setUser((prevUser) => ({ ...prevUser, ...userData })); const elapsedTime = Math.floor((Date.now() - userData.startTime) / 1000); const remainingTime = userData.countdown - elapsedTime; // Start countdown if necessary if (elapsedTime >= userData.countdown) { await updateUserInFirestore({ isSpinning: false }); setCoins(user.countdown); setShowClaimButton(true); // Show claim button if countdown is completed setIsSpinning(false); setTimer(null); } else { startCountdown(remainingTime); } } } catch (error) { console.error('Error fetching user state:', error); } } }; // Perform initial fetch only once when user.isSpinning is true if (user && user.isSpinning) { fetchUserState(); } }, [user, startCountdown]); </code>
   const userDocRef = doc(db, 'users', user.id); // Adjust the path to your Firestore collection
   await setDoc(userDocRef, data, { merge: true });
 };

 useEffect(() => {
   const fetchUserState = async () => {
     
     if (user && !user.anotherStart) {
       toggleSpin();
       const userDocRef = doc(db, 'users', user.id);
 
       try {
         const userDoc = await getDoc(userDocRef);
         if (userDoc.exists()) {
           const userData = userDoc.data();
 
           setUser((prevUser) => ({
             ...prevUser,
             ...userData
           }));
 
           const elapsedTime = Math.floor((Date.now() - userData.startTime) / 1000);
           const remainingTime = userData.countdown - elapsedTime;
           // Start countdown if necessary
           if (elapsedTime >= userData.countdown) {
             await updateUserInFirestore({ isSpinning: false });
             setCoins(user.countdown);
             setShowClaimButton(true); // Show claim button if countdown is completed
             setIsSpinning(false);
             setTimer(null);
           } else {
             startCountdown(remainingTime);
           }
         }
       } catch (error) {
         console.error('Error fetching user state:', error);
       }
     }
     
   };
 
   // Perform initial fetch only once when user.isSpinning is true
   if (user && user.isSpinning) {
     fetchUserState();
   }
   
   
 }, [user, startCountdown]);

Here is startCountdown:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> const startCountdown = (initialTime) => {
let timeLeft = initialTime;
setTimer(formatTime(timeLeft));
countdownRef.current = setInterval(() => {
setCoins((prev) => prev + user.speed); // Increment coins based on user speed
timeLeft -= 1;
setProgress(((initialTime - timeLeft) / initialTime) * 100);
setTimer(formatTime(timeLeft));
if (timeLeft <= 0) {
clearInterval(countdownRef.current);
setIsSpinning(false);
setTimer(null);
setShowClaimButton(true);
updateUserInFirestore({ isSpinning: false, coins: coins + user.speed, progress: 100 });
}
}, 1000);
};
</code>
<code> const startCountdown = (initialTime) => { let timeLeft = initialTime; setTimer(formatTime(timeLeft)); countdownRef.current = setInterval(() => { setCoins((prev) => prev + user.speed); // Increment coins based on user speed timeLeft -= 1; setProgress(((initialTime - timeLeft) / initialTime) * 100); setTimer(formatTime(timeLeft)); if (timeLeft <= 0) { clearInterval(countdownRef.current); setIsSpinning(false); setTimer(null); setShowClaimButton(true); updateUserInFirestore({ isSpinning: false, coins: coins + user.speed, progress: 100 }); } }, 1000); }; </code>
 const startCountdown = (initialTime) => {
   let timeLeft = initialTime;
   setTimer(formatTime(timeLeft));
   countdownRef.current = setInterval(() => {
     setCoins((prev) => prev + user.speed); // Increment coins based on user speed
     timeLeft -= 1;
     setProgress(((initialTime - timeLeft) / initialTime) * 100);
     setTimer(formatTime(timeLeft));
 
     if (timeLeft <= 0) {
       clearInterval(countdownRef.current);
       setIsSpinning(false);
       setTimer(null);
       setShowClaimButton(true);
       updateUserInFirestore({ isSpinning: false, coins: coins + user.speed, progress: 100 });
     }
   }, 1000);
 };

For toggleSpin:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> const coinElement = coinRef.current;
if (coinElement) {
coinElement.classList.toggle('spin');
}
setIsSpinning(!isSpinning);
setSpinSpeed((prevSpeed) => Math.min(prevSpeed + user.speed, 10)); // Increase speed
};
</code>
<code> const coinElement = coinRef.current; if (coinElement) { coinElement.classList.toggle('spin'); } setIsSpinning(!isSpinning); setSpinSpeed((prevSpeed) => Math.min(prevSpeed + user.speed, 10)); // Increase speed }; </code>
    const coinElement = coinRef.current;
    if (coinElement) {
      coinElement.classList.toggle('spin');
    }
    setIsSpinning(!isSpinning);
    setSpinSpeed((prevSpeed) => Math.min(prevSpeed + user.speed, 10)); // Increase speed
  };

Please review and help, i have tried many logics but none works. I want the increment to be in every seconds, i have set the timer to 1000, i dont know if it is the useEffect causing it to behave that way. I added clearInterval to avoid memory leaks but it preventing the timer to show it ticking in real-time. Thank you!

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật