Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda