expiry.js
1.2 kB · javascript · 48 lines
1const pad = (n) => String(n).padStart(2, '0');23function label(left) {4 const s = Math.floor(left / 1000);5 const d = Math.floor(s / 86400);6 const h = Math.floor((s % 86400) / 3600);7 const m = Math.floor((s % 3600) / 60);8 if (s < 3600) return `${pad(m)}m ${pad(s % 60)}s left`;9 if (d) return `${d}d ${pad(h)}h ${pad(m)}m left`;10 return `${h}h ${pad(m)}m left`;11}1213function expired() {14 for (const button of document.querySelectorAll('[data-add]')) button.disabled = true;15 for (const buy of document.querySelectorAll('[data-buy]')) {16 buy.removeAttribute('href');17 buy.setAttribute('aria-disabled', 'true');18 }19}2021function tick() {22 const node = document.querySelector('[data-expiry]');23 if (!node) return true;24 const left = Number(node.dataset.expiry) - Date.now();25 if (left <= 0) {26 node.textContent = 'Expired';27 expired();28 return true;29 }30 node.textContent = label(left);31 node.dataset.ttl = String(left);32 return false;33}3435let timer = 0;3637function run() {38 clearInterval(timer);39 if (document.hidden) return;40 if (tick()) return;41 timer = setInterval(() => {42 if (tick()) clearInterval(timer);43 }, 1000);44}4546document.addEventListener('visibilitychange', run);47window.addEventListener('flip', run);48run();