Il problema è che usi variabili globali che quindi si sovrascrivono ogni volta. In ogni caso, se fossi in te, io imposterei tutto diversamente…:
codice:<!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>CountDown</title> <script type="text/javascript"> function Timer (sId, nYear, nMonth, nDay, nHour, nMinute, nSeconds) { if (arguments.length < 2) { throw new TypeError("Timer - not enough arguments"); } var domNode = document.getElementById(sId); this.expires = (new Date(nYear, nMonth - 1, nDay, nHour, nMinute, nSeconds)).getTime() || 0x1f3fffffc18; this.id = sId; if (domNode) { this.owner = domNode; } Timer.instances.push(this); } Timer.refreshAll = function () { for (var nDelta, nDLeft, nHLeft, nMLeft, nSLeft, oThis, oDisplay, nInst = 0; nInst < Timer.instances.length; nInst++) { oThis = Timer.instances[nInst]; if (!oThis) { continue; } if (oThis.hasOwnProperty("owner")) { oDisplay = oThis.owner } else if (oDisplay = document.getElementById(oThis.id)) { oThis.owner = oDisplay; } else { continue; } nDelta = oThis.expires - Date.now(); // Casual expiration test // if (Math.floor(Math.random() * 8) === 0) { nDelta = 0; } if (nDelta <= 0) { Timer.instances[nInst] = null; oDisplay.innerHTML = "Tempo scaduto"; continue; } nDLeft = Math.floor(nDelta / 864e5); nDelta -= (nDLeft * 864e5); nHLeft = Math.floor(nDelta / 36e5); nDelta -= (nHLeft * 36e5); nMLeft = Math.floor(nDelta / 6e4); nDelta -= (nMLeft * 6e4); nSLeft = Math.floor(nDelta / 1e3); nDelta -= (nSLeft * 1e3); oDisplay.innerHTML = nDLeft + " giorni, " + nHLeft + " ore, " + nMLeft + " minuti e " + nSLeft + " secondi"; } }; Timer.instances = []; Timer.session = setInterval(Timer.refreshAll, 1000); </script> </head> <body> <div id="div2"></div> <script> var tdiv2 = new Timer("div2", 2019, 02, 26, 21, 00, 31); </script> <div id="div3"></div> <script> var tdiv3 = new Timer("div3", 2013, 04, 26, 23, 00, 00); </script> </body> </html>![]()

Rispondi quotando