Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

220
Vistas
Coutdown from local storage isn't working while browser/site is closed
if(localStorage.getItem("total_seconds")){
    var total_seconds = localStorage.getItem("total_seconds");
    
} 
else {
        var total_seconds = 10*10;
} 
var minutes = parseInt(total_seconds/60);
var seconds = parseInt(total_seconds%60);

function countDownTimer(){
    if(seconds < 10){
        seconds= "0"+ seconds ;
    }
    if(minutes < 10){
        minutes= "0"+ minutes ;
}
document.getElementById("timer").innerHTML = "Result after:&nbsp; "+minutes+"&nbsp;minutes "+seconds+"&nbsp;seconds";
    if(total_seconds <= 0){
        setTimeout("document.quiz.submit()" ,1);
        document.getElementById("timer").innerHTML = "";
        localStorage.removeItem("total_seconds");
   } else {
         total_seconds = total_seconds -1 ;
        minutes = parseInt(total_seconds/60);
        seconds = parseInt(total_seconds%60);
        localStorage.setItem("total_seconds",total_seconds)
        setTimeout("countDownTimer()" ,1000);
        } 
}setTimeout("countDownTimer()" ,1000);
        

    

Above is the code i am using for coutdown using local storage but it doesn't count downs and resume where the user has left if site/browser is closed any tips on how to make it so the coutdown could even work if the user isn't at site or have closed his browser.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your code only runs while the client browser is open. If your script should look & behave in the way your current code does you will need a server. However, we can make use of the built-in Date object in JavaScript in order to detect how long has passed since the creation of the timer:

const DEFAULT_TIMER_DURATION = 10; // In seconds.

// Here, we get the status of the currently-active timer:
let totalSeconds = parseInt(localStorage.getItem("total_seconds"));
let startDate = parseInt(localStorage.getItem("start_date"));
if(!(totalSeconds && startDate)) {
    // If there isn't an active timer, set one up:
    localStorage.setItem("total_seconds", DEFAULT_TIMER_DURATION);
    localStorage.setItem("start_date", new Date().getTime());
    totalSeconds = DEFAULT_TIMER_DURATION;
    startDate = new Date().getTime();
    console.log("Reset timer:", DEFAULT_TIMER_DURATION);
}


// This function updates the timer and displays the countdown:
function displayElapsedSecond(timerData) {
    if(timerData.secondsLeft <= 0) {
        console.log("Time is up!");
        localStorage.removeItem("total_seconds");
        localStorage.removeItem("start_date");
        return;
    }
    if(timerData.initialDelay) {
        setTimeout(() => {
            displayElapsedSecond({secondsLeft: timerData.secondsLeft});
        }, initialDelay);
        return;
    }
    timerData.secondsLeft--;
    console.log("Seconds left:", timerData.secondsLeft);
    setTimeout(() => {
        displayElapsedSecond({secondsLeft: timerData.secondsLeft});
    }, 1000);
}


// this block of code calculates how long has passed and continues counting down from wherever the user left of:
const now = new Date().getTime();
const secondsPassed = (now - startDate) / 1000;
let secondsLeft = totalSeconds - secondsPassed;
const initialDelay = Math.ceil(secondsLeft) - secondsLeft;
secondsLeft = Math.ceil(secondsLeft);

displayElapsedSecond({initialDelay, secondsLeft});

// Obviously some improvements can be made for time complexity, but the code nicely illustrates the way this timer works
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda