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

着陆页定时跳转及Cookie续时功能故障技术咨询

Hey there! Let's work through this problem together—you've got a clear goal, and we can fix those two key pain points (no return to the original discount after redirect, and resuming the timer when users come back) with some adjusted cookie logic and a bit of targeted code.

Core Issues to Fix

First, let's break down why your initial 10-second cookie write didn't hit the mark:

  • Storing just remaining time can lead to calculation errors when the user closes/reopens the page
  • You didn't have a mechanism to block users from returning to the original discount page after redirect
  • Infrequent cookie updates (10s) might miss saving the latest state if the user closes the page mid-interval

Complete Solution

Here's a refined approach that addresses all your requirements:

Step 1: Persist the Timer with End Timestamps (Not Remaining Time)

Instead of saving remaining seconds, store the exact timestamp when the timer should end. This eliminates calculation errors and makes resuming the timer trivial. We'll also add a cookie to track if the user was already redirected.

// Initialize the discount timer logic
function initDiscountTimer() {
  // Configuration - adjust these values to match your setup
  const CONFIG = {
    redirectDelayMs: 20 * 60 * 1000, // 20 minutes in milliseconds
    targetPageUrl: '/your-other-discount-page.html', // Replace with your target URL
    cookieExpiryDays: 7, // Keep redirect flag active for 7 days
    timerDisplayId: 'timer-display' // ID of element to show remaining time (optional)
  };

  // Cookie names for persistence
  const COOKIES = {
    timerEnd: 'discount_timer_end',
    hasRedirected: 'discount_has_redirected'
  };

  // First, block access to original discount page if user was already redirected
  if (getCookie(COOKIES.hasRedirected) === 'true') {
    window.location.href = CONFIG.targetPageUrl;
    return;
  }

  let timerEndTime;
  // Check if we have a saved timer end time from a previous session
  const savedEndTime = getCookie(COOKIES.timerEnd);
  if (savedEndTime) {
    timerEndTime = parseInt(savedEndTime, 10);
  } else {
    // No saved time - set a new end time
    timerEndTime = Date.now() + CONFIG.redirectDelayMs;
    setCookie(COOKIES.timerEnd, timerEndTime, CONFIG.cookieExpiryDays);
  }

  // Update the timer display and persistence every second
  function updateTimer() {
    const now = Date.now();
    const remainingMs = timerEndTime - now;

    // Time's up - redirect and mark as redirected
    if (remainingMs <= 0) {
      setCookie(COOKIES.hasRedirected, 'true', CONFIG.cookieExpiryDays);
      window.location.href = CONFIG.targetPageUrl;
      return;
    }

    // Optional: Update on-page timer display
    if (CONFIG.timerDisplayId) {
      const minutes = Math.floor(remainingMs / (1000 * 60));
      const seconds = Math.floor((remainingMs % (1000 * 60)) / 1000);
      document.getElementById(CONFIG.timerDisplayId).textContent = 
        `${minutes}:${seconds.toString().padStart(2, '0')}`;
    }

    // Save the current end time to cookie (1s interval is low-overhead)
    setCookie(COOKIES.timerEnd, timerEndTime, CONFIG.cookieExpiryDays);
    setTimeout(updateTimer, 1000);
  }

  // Helper: Set a cookie with expiry
  function setCookie(name, value, daysToLive) {
    const date = new Date();
    date.setTime(date.getTime() + (daysToLive * 24 * 60 * 60 * 1000));
    const expires = `expires=${date.toUTCString()}`;
    document.cookie = `${name}=${value}; ${expires}; path=/; SameSite=Lax`;
  }

  // Helper: Read a cookie value
  function getCookie(name) {
    const nameEQ = `${name}=`;
    const cookieArray = document.cookie.split(';');
    for (let i = 0; i < cookieArray.length; i++) {
      let cookie = cookieArray[i];
      while (cookie.charAt(0) === ' ') cookie = cookie.substring(1);
      if (cookie.indexOf(nameEQ) === 0) return cookie.substring(nameEQ.length);
    }
    return null;
  }

  // Start the timer when the page loads
  updateTimer();
}

// Initialize the timer on page load
window.addEventListener('load', initDiscountTimer);

Step 2: Key Improvements Explained

  • End Timestamp Storage: Using a timestamp for when the timer ends ensures accurate resuming, even if the user closes the page for hours.
  • Redirect Blocking: The discount_has_redirected cookie prevents users from returning to the original 90% discount page—whether they use the back button or manually enter the URL.
  • Frequent Cookie Updates: Saving the end time every second ensures the latest state is always persisted, avoiding lost progress if the user closes the page mid-interval.
  • User Visibility: Optional on-page timer display keeps users informed about how much time they have left (just add an element with ID timer-display to your landing page).

Test Scenarios to Validate

Make sure to test these edge cases to ensure everything works:

  1. User stays on the page for 20 minutes → auto-redirects, and can't return to the original page.
  2. User closes the page after 5 minutes → reopens, timer resumes at 15 minutes remaining.
  3. User clears cookies → reopens the original page, timer starts fresh at 20 minutes.

内容的提问来源于stack exchange,提问作者Yaniv Lev Ari

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:28:25