Clear order data timer

User
(function () {
const DURATION = 5 * 60 * 1000; // 20 minutes
const DEADLINE_KEY = "cart_deadline"; // localStorage key
const ORDER_KEY = "fossettsOrderData"; // your order data key

// Get deadline from localStorage or set new
let deadline = localStorage.getItem(DEADLINE_KEY);
if (!deadline) {
deadline = Date.now() + DURATION;
localStorage.setItem(DEADLINE_KEY, deadline);
} else {
deadline = parseInt(deadline, 10);
}

function updateTimers() {
const now = Date.now();
let remaining = deadline – now;

if (remaining {
el.textContent = "00:00";
});
clearInterval(timerInterval);

// Clear storage after time up
localStorage.removeItem(DEADLINE_KEY);

localStorage.removeItem(ORDER_KEY);

console.log("⏰ Time's up — fossettsOrderData cleared");
window.location.href = "/";
return;
}

const minutes = Math.floor(remaining / 1000 / 60);
const seconds = Math.floor((remaining / 1000) % 60);

const formatted =
`Complete your order in ${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")} minutes`;

document.querySelectorAll(".order_timer").forEach(el => {
el.innerHTML = formatted;
});
}

// Start ticking
updateTimers();
const timerInterval = setInterval(updateTimers, 1000);
})();
also clear orderData js arrray and call custom function updateOrderSummary() when time expire

Assistant
<script>
(function () {
  const DURATION = 20 * 60 * 1000; // 20 minutes
  const DEADLINE_KEY = "cart_deadline"; // localStorage key
  const ORDER_KEY = "fossettsOrderData"; // your order data key

  // Get deadline from localStorage or set new
  let deadline = localStorage.getItem(DEADLINE_KEY);
  if (!deadline) {
    deadline = Date.now() + DURATION;
    localStorage.setItem(DEADLINE_KEY, String(deadline));
  } else {
    deadline = parseInt(deadline, 10);
  }

  function clearOrderAndRefreshUI() {
    // Clear localStorage keys
    localStorage.removeItem(DEADLINE_KEY);
    localStorage.removeItem(ORDER_KEY);

    // Clear in-memory JS orderData, if present
    if (typeof window.orderData === "object" && window.orderData) {
      try {
        // normalize to your expected structure
        window.orderData.tickets = Array.isArray(window.orderData.tickets) ? [] : [];
        window.orderData.addOns  = Array.isArray(window.orderData.addOns)  ? [] : [];
        window.orderData.total   = 0;
      } catch (e) {
        // fallback: hard reset
        window.orderData = { tickets: [], addOns: [], total: 0 };
      }
    }

    // Call custom UI updater if available
    if (typeof window.updateOrderSummary === "function") {
      try { window.updateOrderSummary(); } catch (_) {}
    }
  }

  function updateTimers() {
    const now = Date.now();
    let remaining = deadline - now;

    if (remaining <= 0) {
      document.querySelectorAll(".order_timer").forEach(el => {
        el.textContent = "00:00";
      });
      clearInterval(timerInterval);

      clearOrderAndRefreshUI();

      console.log("⏰ Time's up — order cleared");
      window.location.href = "/";
      return;
    }

    const minutes = Math.floor(remaining / 1000 / 60);
    const seconds = Math.floor((remaining / 1000) % 60);

    const formatted =
      `<div style="font-weight: bold;font-size:24px">Complete your order in ${minutes.toString().padStart(2, "0")}:${seconds.toString().padStart(2, "0")} minutes</div>`;

    document.querySelectorAll(".order_timer").forEach(el => {
      el.innerHTML = formatted;
    });
  }

  // Start ticking
  updateTimers();
  const timerInterval = setInterval(updateTimers, 1000);
})();
</script>
User
but the problem is can not get updated data
Assistant
You’re probably mutating a different copy than the UI reads, or your UI only reads from `localStorage` once. Fix by (1) keeping a single global `orderData` object, (2) mutating it in-place, (3) emitting an event the UI can listen for, and (4) calling `updateOrderSummary()` right after clearing.

Drop-in replacement (keeps timer logic, plus reliable updates):

<script>
(function () {
  const DURATION = 20 * 60 * 1000; // 20 minutes
  const DEADLINE_KEY = "cart_deadline";
  const ORDER_KEY = "fossettsOrderData";

  // Ensure one global object is used everywhere
  if (!window.orderData || typeof window.orderData !== "object") {
    try {
      window.orderData = JSON.parse(localStorage.getItem(ORDER_KEY)) || { tickets: [], addOns: [], total: 0 };
    } catch {
      window.orderData = { tickets: [], addOns: [], total: 0 };
    }
  }

  // Helpers to read/write and keep globals + storage in sync
  function setOrderData(next) {
    // mutate in-place so any references stay valid
    Object.assign(window.orderData, next);
    try { localStorage.setItem(ORDER_KEY, JSON.stringify(window.orderData)); } catch {}
    // notify listeners (optional)
    window.dispatchEvent(new CustomEvent('order:updated', { detail: window.orderData }));
  }

  // Deadline setup
  let deadline = parseInt(localStorage.getItem(DEADLINE_KEY) || "", 10);
  if (Number.isNaN(deadline)) {
    deadline = Date.now() + DURATION;
    localStorage.setItem(DEADLINE_KEY, String(deadline));
  }

  function clearOrderAndRefreshUI() {
    // clear storage
    localStorage.removeItem(DEADLINE_KEY);
    localStorage.removeItem(ORDER_KEY);

    // mutate the SAME object (don't replace the reference)
    setOrderData({ tickets: [], addOns: [], total: 0 });

    // call your UI refresh hook if present
    if (typeof window.updateOrderSummary === "function") {
      try { window.updateOrderSummary(); } catch {}
    }

    // optional: broadcast a specific "expired" event
    window.dispatchEvent(new CustomEvent('order:expired'));
  }

  function updateTimers() {
    const now = Date.now();
    const remaining = deadline - now;

    if (remaining <= 0) {
      document.querySelectorAll(".order_timer").forEach(el => el.textContent = "00:00");
      clearInterval(timerInterval);

      clearOrderAndRefreshUI();

      // Show a message before redirecting (or replace with your modal)
      const banner = document.querySelector(".cart-expired-banner");
      if (banner) {
        banner.textContent = "Cart expired — please start over.";
        banner.style.display = "block";
      }

      // redirect if you want (comment out if you prefer a modal-first UX)
      window.location.href = "/";
      return;
    }

    const minutes = Math.floor(remaining / 1000 / 60);
    const seconds = Math.floor((remaining / 1000) % 60);
    const formatted =
      `<div style="font-weight: bold;font-size:24px">Complete your order in ${String(minutes).padStart(2,"0")}:${String(seconds).padStart(2,"0")} minutes</div>`;

    document.querySelectorAll(".order_timer").forEach(el => el.innerHTML = formatted);
  }

  // Kick off
  updateTimers();
  const timerInterval = setInterval(updateTimers, 1000);

  // (Optional) keep multiple tabs in sync: if one tab clears, others update too
  window.addEventListener('storage', (e) => {
    if (e.key === ORDER_KEY && e.newValue === null) {
      // another tab cleared the order
      setOrderData({ tickets: [], addOns: [], total: 0 });
      if (typeof window.updateOrderSummary === "function") {
        try { window.updateOrderSummary(); } catch {}
      }
    }
    if (e.key === DEADLINE_KEY && e.newValue === null) {
      // another tab expired
      clearInterval(timerInterval);
      document.querySelectorAll(".order_timer").forEach(el => el.textContent = "00:00");
    }
  });
})();
</script>

Why this fixes “can’t get updated data”:
– We **do not replace** `window.orderData`; we **mutate it in place** so any other code holding a reference sees the change immediately.
– We **sync localStorage** and the global every time via `setOrderData(…)`.
– We **call `updateOrderSummary()`** right after clearing.
– We **emit events** (`order:updated`, `order:expired`) if your UI prefers to listen instead of being directly called.

If you still see stale values, search for places that `const orderData = …` (captured once) or that read from `localStorage` only on page load. Switch those to use `window.orderData` or listen for `order:updated`.

User
quantitySelector=document.querySelector(".quantity-value");
quantitySelector.forEach(el => {
el.value = "0";
});
this is input class and not working
Assistant
That’s because `document.querySelector(".quantity-value")` only gives you **the first element**.
If you have multiple “, you need **querySelectorAll** which returns a NodeList you can loop over.

Here’s the correct way:

const quantitySelectors = document.querySelectorAll(".quantity-value");

quantitySelectors.forEach(el => {
  el.value = "0"; // reset each input’s value
});

If you only ever have one input and want to reset it:

const quantitySelector = document.querySelector(".quantity-value");
if (quantitySelector) {
  quantitySelector.value = "0";
}

✅ Use **`querySelectorAll`** when you expect multiple elements,
✅ Use **`querySelector`** when you only want one.

Do you want me to update your timer-expire cleanup code so it also resets all `.quantity-value` inputs?

Leave a Comment

Your email address will not be published. Required fields are marked *