Estoy creando un proyecto usando JavaScript. He creado un temporizador inverso en segundos. Cuando el temporizador llegue a cero, llamará a alguna función.
Este temporizador funciona bien, pero cuando el navegador entra en modo de suspensión o se minimiza, el temporizador se reanuda.
setTimeout(() => { var counter = 60 let updatedMsg; this.timer = setInterval(() => { counter--; if (counter == 0) { this.processLogout(); clearInterval(this.timer); } console.log(counter) updatedMsg = message.replace("{0}", counter); messageRef.dialogRef.componentInstance.config.message = updatedMsg; }, 1000); }, 500);A continuación se muestran las soluciones de trabajo:
var startTime = new Date() startTime.setTime(startTime.getTime() + 1000 * 120); startTime = Math.floor(startTime / 1000); function startTimeCounter() { var now = Math.floor(Date.now() / 1000); var diff = startTime - now ; var s = Math.floor(diff); console.log(s) } setInterval(() => { startTimeCounter() }, 1000);En lugar de usar un valor que incrementa/disminuye cuando se llama a una devolución de llamada, debe calcular cuándo debe finalizar su cuenta regresiva. Luego compare la hora actual con este objetivo.
const MILLISECOND = 1; const SECOND = 1000*MILLISECOND; const MINUTE = 60*SECOND; const finishAt = Date.now() + 1*MINUTE; const intervalID = setInterval(() => { const now = Date.now(); if (now < finishAt) { // code that is executed at a 1 second interval (if the browser is active) const msToGo = finishAt - now; const secToGo = Math.floor(msToGo / SECOND); console.log(secToGo); } else { clearInterval(intervalID); // code to be executed when your timer finishes console.log("done"); } }, 1*SECOND); const MILLISECOND = 1; const SECOND = 1000*MILLISECOND; const MINUTE = 60*SECOND; const finishAt = Date.now() + 10*SECOND; const intervalID = setInterval(() => { const now = Date.now(); if (now < finishAt) { // code that is executed at a 1 second interval (if the browser is active) const msToGo = finishAt - now; const secToGo = Math.floor(msToGo / SECOND); console.log(secToGo); } else { clearInterval(intervalID); // code to be executed when your timer finishes console.log("done"); } }, 1*SECOND);Otra opción sería crear 2 devoluciones de llamada. Uno que tiene un intervalo de 1 segundo que ejecuta algún código en un intervalo específico. La otra devolución de llamada es un tiempo de espera que detiene el intervalo.
const duration = 1*MINUTE; const finishAt = Date.now() + duration; const intervalID = setInterval(() => { // code that is executed at a 1 second interval (if the browser is active) const msToGo = finishAt - Date.now(); const secToGo = Math.floor(msToGo / SECOND); console.log(secToGo); }, 1*SECOND); setTimeout(() => { clearInterval(intervalID); // code to be executed when your timer finishes console.log("done"); }, duration); const MILLISECOND = 1; const SECOND = 1000*MILLISECOND; const MINUTE = 60*SECOND; const duration = 10*SECOND; const finishAt = Date.now() + duration; const intervalID = setInterval(() => { // code that is executed at a 1 second interval (if the browser is active) const msToGo = finishAt - Date.now(); const secToGo = Math.floor(msToGo / SECOND); console.log(secToGo); }, 1*SECOND); setTimeout(() => { clearInterval(intervalID); // code to be executed when your timer finishes console.log("done"); }, duration); Esta segunda solución podría eliminar un intervalo si la devolución de llamada setTimeout() se ejecuta antes del último tic de setInterval() . Pero en la mayoría de los escenarios esto no debería ser un problema.