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

132
Visualizações
How can I override a JavaScript variable when page is visible again?

When visiting a web page I want to declare a start time and send an AJAX request when the user leaves the site. It works like expected but when changing the tab or minimizing the browser the start time remains the same as when the user accessed the web page. I thought I could override the start time by declaring it within a function which is fired when the tab is active again but with no success.

Here is my code so far:

$(document).ready(function() {
    var starts = Math.ceil(Date.now() / 1000);
    
    //declare new start time when user returns
    document.addEventListener('visibilitychange', function() {
        if(!document.hidden) {
            var starts = Math.ceil(Date.now() / 1000);
        }
    });

    //AJAX
    //value of old starts is used here instead of new declared starts
    ...
});

Does anyone have a solution for this?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try document.visibilityState === 'visible' so your code will look like this:

$(document).ready(function() {
    var starts = Math.ceil(Date.now() / 1000);
    
    //declare new start time when user returns
    document.addEventListener('visibilitychange', function() {
        if(document.visibilityState === 'visible') {
            var starts = Math.ceil(Date.now() / 1000);
        }
    });
});

Read more about it here:

https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event

about 4 years ago · Juan Pablo Isaza Relatório

0

const timer = document.querySelector("#timer");

window.addEventListener('DOMContentLoaded', () => {
  startTimer(); // starttime on load
});
let intervalID = null;
let timerValue = 0;
const startTimer = () => {
  intervalID = setInterval(() => {
    timerValue++;
    timer.innerText = timerValue;
  }, 1000);
}

const stopTimer = () => {
  clearInterval(intervalID);
}

document.addEventListener('visibilitychange', () => {
  if (document.hidden) { // codition for browser tabs is active or minimize
    stopTimer(); // stop timer when you leave tab minimize it on
    return;
  }
  startTimer(); // start timer when you comback to tab maximize it
})
<div class="container">
  <h2>time spend in seconds:<span id="timer">0</span>
    <h2>
</div>

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