You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

页面刷新不重启的促销倒计时计时器实现求助(附代码)

Fixing Timer Reset on Page Refresh with Cookies

Got it, let's resolve that timer reset issue you're facing! The core problem right now is that every page reload generates a brand new 15-day deadline. By storing the initial deadline in a cookie, we can make the timer persist across sessions and reloads. Here's how to integrate cookie handling into your existing code:

First, we'll add two simple utility functions to handle reading and setting cookies. These will make it easy to store and retrieve the deadline:

// Helper function to get a cookie by name
function getCookie(name) {
    let value = "; " + document.cookie;
    let 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) {
    document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/`;
}

Step 2: Modify Deadline Initialization

Instead of always generating a new deadline, we'll first check if we already have one stored in a cookie. If not, we'll create a new deadline and save it to the cookie:

// Check if we have a saved deadline in cookies
let savedDeadline = getCookie('promoDeadline');
let deadline;

if (savedDeadline) {
    // Use the saved deadline if it exists and is still in the future
    deadline = new Date(savedDeadline);
    if (deadline <= new Date()) {
        // If saved deadline is already past, generate a new one
        deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
        setCookie('promoDeadline', deadline, deadline);
    }
} else {
    // No saved deadline, create a new one and store it
    deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
    setCookie('promoDeadline', deadline, deadline);
}

Step 3: Full Updated Code

Here's your complete code with cookie integration, all put together:

function getTimeRemaining(endtime) {
    var t = Date.parse(endtime) - Date.parse(new Date());
    var seconds = Math.floor((t / 1000) % 60);
    var minutes = Math.floor((t / 1000 / 60) % 60);
    var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
    var days = Math.floor(t / (1000 * 60 * 60 * 24));
    return {
        'total': t,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
    };
}

function initializeClock(id, endtime) {
    var clock = document.getElementById(id);
    var daysSpan = clock.querySelector('.days');
    var hoursSpan = clock.querySelector('.hours');
    var minutesSpan = clock.querySelector('.minutes');
    var secondsSpan = clock.querySelector('.seconds');

    function updateClock() {
        var t = getTimeRemaining(endtime);
        daysSpan.innerHTML = t.days;
        hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
        minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
        secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);

        if (t.total <= 0) {
            clearInterval(timeinterval);
            // Optional: Clear the cookie once the timer ends
            document.cookie = "promoDeadline=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
        }
    }

    updateClock();
    var timeinterval = setInterval(updateClock, 1000);
}

// Cookie helper functions
function getCookie(name) {
    let value = "; " + document.cookie;
    let parts = value.split("; " + name + "=");
    if (parts.length === 2) return parts.pop().split(";").shift();
}

function setCookie(name, value, expires) {
    document.cookie = `${name}=${value}; expires=${expires.toUTCString()}; path=/`;
}

// Initialize deadline with cookie persistence
let savedDeadline = getCookie('promoDeadline');
let deadline;

if (savedDeadline) {
    deadline = new Date(savedDeadline);
    if (deadline <= new Date()) {
        deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
        setCookie('promoDeadline', deadline, deadline);
    }
} else {
    deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
    setCookie('promoDeadline', deadline, deadline);
}

initializeClock('clockdiv', deadline);

Key Notes

  • The cookie will automatically expire when the promotion ends, so users will get a fresh timer once the current promo is over.
  • We added a check to make sure if the saved deadline is already in the past (e.g., if someone clears their cookies mid-promo but comes back after it ended), we'll generate a new one.
  • The path=/ ensures the cookie is accessible across your entire site, not just the current page.

内容的提问来源于stack exchange,提问作者AKUPOID

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:20:41