mientras trato de ejecutar el temporizador en mi página web en el botón, haga clic en la página cargada y el temporizador se muestra durante un tiempo y cuando la página se carga completamente, el temporizador desaparece en el código de la página siguiente.
// Set the date we're counting down to function StartTimer() { debugger; // var countDownDate = new Date("Jan 10, 2022").getTime(); var countDownDate = new Date().getTime()+10000; // Update the count down every 1 second var x = setInterval(function() { // Get today's date and time var now = new Date().getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Output the result in an element with id="demo" document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + " " + seconds + "s "; // If the count down is over, write some text debugger; if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; } }, 1000); } StartTimer(); <p id="demo"></p>Realmente no necesita calcular la hora actual en su devolución de llamada setInterval() cada vez. La devolución de llamada se llamará repetidamente en intervalos de un segundo. Simplemente podría disminuir el número de segundos inicialmente calculado ( diff ) y usarlo como la fuente del "tiempo restante":
const p=document.getElementById("demo"); function StartTimer(endTime) { const units=[[86400,3600,60,1],"days,hours,minutes,seconds".split(",")]; // remaining time in seconds: var diff = Math.round((endTime - new Date().getTime()) / 1000); // Update the count-down once every second (=1000ms): var x = setInterval(function() { const d=[]; // array with [days,hours,minutes,sconds] of remaining time units[0].reduce((a,c)=>(d.push(~~(a/c)),a%c),diff); // calculate d here! p.textContent=d.map((c,i)=>`${c} ${units[1][i]}`) .join(", ")+" to go."; if (diff--<1) { clearInterval(x); p.innerHTML = "EXPIRED"; } }, 1000); } const endTime=new Date(new Date().getTime()+10000); // 10 seconds into the future console.log("end time:",endTime) StartTimer(endTime); <p id="demo"></p>