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

129
Vistas
Timer shows wrong results
var seconds_lapsed = 0;

function tick() {    
    seconds_lapsed++;
}

function countup() { 
    setTimeout(function () {
        if (stopped) return; // stop the loop
        if (!is_paused()) {
            tick();
            show_time_left();            
        }
        countup(); // <--- this is the "loop"
    }, 1000);
}

This is the core of my timer. Of course I have some view to represent the result. But ticking is done here.

The problem

It shows wrong time. Have a look at this:

enter image description here

The timer was set for 3 hours. Twelve minutes lapsed. And the discrepancy is almost 1.5 minutes.

In the other window the timer by Google is working. This one:

enter image description here

So, I just compared my timer with that of google. I started them almost at once. The difference should be no more than a couple of seconds (to switch the window and press the button).

What is the reason for this, and how can I correct it?

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

0

setTimeout with an interval of 1000 does NOT run exactly after every 1 seconds. It schedules to run after 1 second, but can be delayed with by actions running at that time.

A better way of solving this is by calculating via date difference. I took your sample (added the missing vars/funcs) and changed the tick() function to use date diffs.

var seconds_lapsed = 0;
var startDateTime = new Date();
var stopped = false;
var is_paused = function() { return false; }

function tick() {    
    datediffInms =  new Date() - startDateTime;
    seconds_lapsed = Math.round(datediffInms / 1000);
}

function countup() { 
    setTimeout(function () {
        if (stopped) return; // stop the loop
        if (!is_paused()) {
            tick();
            //show_time_left();            
            console.log(seconds_lapsed)
        }
        countup(); // <--- this is the "loop"
    }, 1000);
}


countup();
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