Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

131
Views
¿Cómo puedo anular una variable de JavaScript cuando la página vuelve a estar visible?

Cuando visito una página web, quiero declarar una hora de inicio y enviar una solicitud AJAX cuando el usuario abandona el sitio. Funciona como se esperaba, pero al cambiar de pestaña o minimizar el navegador, la hora de inicio sigue siendo la misma que cuando el usuario accedió a la página web. Pensé que podría anular la hora de inicio declarándola dentro de una función que se activa cuando la pestaña vuelve a estar activa pero sin éxito.

Aquí está mi código hasta ahora:

 $(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 ... });

¿Alguien tiene una solución para esto?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Pruebe document.visibilityState === 'visible' para que su código se vea así:

 $(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); } }); });

Lea más sobre esto aquí:

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

about 4 years ago · Juan Pablo Isaza Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!