JavaScript Cookie实现跨页面倒计时不重置技术求助
Hey Pascal! Let's get that countdown timer working exactly how you want it—persisting across product pages with cookies, and showing 0h4m26s when users return 12+ hours after their first visit. Here's a complete, tested solution:
Step 1: HTML Structure
First, make sure your product pages have this container for the timer (adjust styling to match your site):
<div id="countdown-timer" style="font-size: 1.2rem; font-weight: bold;"> <span id="hours">12</span>h <span id="minutes">04</span>m <span id="seconds">26</span>s </div>
Step 2: Complete JavaScript with Cookie Integration
Add this script to your product pages (preferably right before the closing </body> tag):
// Helper function to read a cookie by name function getCookie(name) { const value = `; ${document.cookie}`; const parts = value.split(`; ${name}=`); if (parts.length === 2) return parts.pop().split(';').shift(); } // Helper function to set a cookie with expiration function setCookie(name, value, expires) { // Set path=/ so the cookie works across all product pages document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/; SameSite=Lax`; } document.addEventListener('DOMContentLoaded', function() { // Grab timer elements from the DOM const hoursEl = document.getElementById('hours'); const minutesEl = document.getElementById('minutes'); const secondsEl = document.getElementById('seconds'); // Define core timer values const initialTotalSeconds = 12 * 3600 + 4 * 60 + 26; // 12h4m26s in seconds const twelveHoursInSeconds = 12 * 3600; // 12 hours in seconds const sevenDaysInMs = 7 * 24 * 60 * 60 * 1000; // Cookie expiration (7 days) let countdownInterval; let endTime; // Initialize the countdown logic function initCountdown() { const savedStartTime = getCookie('countdownStartTime'); const savedEndTime = getCookie('countdownEndTime'); const now = Date.now() / 1000; // Current time in seconds if (savedStartTime && savedEndTime) { const timeSinceFirstVisit = now - parseInt(savedStartTime); // Case 1: User returns 12+ hours after first visit if (timeSinceFirstVisit >= twelveHoursInSeconds) { updateDisplay(4 * 60 + 26); // Show 0h4m26s return; } // Case 2: User is within 12 hours of first visit endTime = parseInt(savedEndTime); let remainingSeconds = endTime - now; if (remainingSeconds > 0) { // Continue the countdown from where it left off updateDisplay(remainingSeconds); startCountdown(remainingSeconds); } else { // Countdown already finished, show 00:00:00 updateDisplay(0); } } else { // Case 3: First time visiting - start fresh const startTime = now; endTime = startTime + initialTotalSeconds; // Save start/end times to cookies (expire after 7 days) setCookie('countdownStartTime', startTime, new Date(Date.now() + sevenDaysInMs)); setCookie('countdownEndTime', endTime, new Date(Date.now() + sevenDaysInMs)); updateDisplay(initialTotalSeconds); startCountdown(initialTotalSeconds); } } // Update the timer display with formatted values function updateDisplay(totalSeconds) { const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); const seconds = Math.floor(totalSeconds % 60); // Pad numbers with leading zeros for consistency hoursEl.textContent = String(hours).padStart(2, '0'); minutesEl.textContent = String(minutes).padStart(2, '0'); secondsEl.textContent = String(seconds).padStart(2, '0'); } // Start the countdown interval function startCountdown(remainingSeconds) { // Clear any existing interval to avoid duplicates if (countdownInterval) clearInterval(countdownInterval); countdownInterval = setInterval(() => { remainingSeconds--; endTime--; // Update the end time stored in cookies if (remainingSeconds >= 0) { updateDisplay(remainingSeconds); // Refresh the end time cookie to persist across pages setCookie('countdownEndTime', endTime, new Date(Date.now() + sevenDaysInMs)); } else { // Countdown finished - stop the interval and show 00:00:00 updateDisplay(0); clearInterval(countdownInterval); } }, 1000); } // Kick off the countdown when the page loads initCountdown(); });
Key Features Explained
- Cross-Page Persistence: The
path=/setting ensures cookies are accessible across all your product pages, so the timer continues counting when users navigate between them. - 12-Hour Rule: We save the user's first visit time in a cookie. If they return 12+ hours later, we directly show 0h4m26s as requested.
- Accurate Countdown: Instead of saving just remaining seconds, we save the countdown's end time. This avoids drift if users leave the page and return later.
- Clean Expiration: Cookies expire after 7 days, so after a week, users will see a fresh 12h4m26s countdown again.
How to Test
- Load a product page—you'll see the timer start at 12h4m26s and count down.
- Navigate to another product page—the timer will pick up where it left off.
- Wait 12+ hours (or manually edit the cookie's
countdownStartTimeto a time more than 12 hours ago) and reload—you'll see 0h4m26s.
内容的提问来源于stack exchange,提问作者Pascal
相关产品推荐
相关产品推荐

