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

261
Vistas
Get every ms, sec with javascript
function format(n) { return (n < 10 ? "0" + n : n); }

var hour,min,sec,ms;
function timer() {
    if ((millisecond += 1) == 100) {
        millisecond = 0;
        second++;
    }
    if (second == 60) {
        second = 0;
        minute++;
    }
    if (minute == 60) {
        minute = 0;
        hour++;
    }
    hour = format(hour);
    min = format(minute);
    sec = format(second);
    ms = format(millisecond);
}

I'm using this piece of code to generate timestamps. Check how is the output:

00:00:00.01
00:00:00.02
...
00:00:10.10
00:00:10.11
00:00:10.12
...
00:02:05:01
00:02:05:02
...

It works perfectly! But, I'm using setTimeout and this is very innacurate sometimes. So, my idea is start working with Date.Now(), but when I use it, I got something like this as response:

00:00:00.02
00:00:00.05
00:00:00.07
...
00:00:07.17
00:00:00.21
00:00:00.23
...

It works, but I'm unable to catch every millisecond and second, and this won't fit my need! So, what should I do? Here is the code:

var offset = 0,
paused = true;

render();
  
function startStopwatch(evt) {
    if (paused) {
        paused = false;
        offset -= Date.now();
        render();
    }
}

function stopStopwatch(evt) {
    if (!paused) {
        paused = true;
        offset += Date.now();
    }
}

function resetStopwatch(evt) {
    if (paused) {
        offset = 0;
        render();
    } else {
        offset = -Date.now();
    }
}

function format(value, scale, modulo, padding) {
    value = Math.floor(value / scale) % modulo;
    return value.toString().padStart(padding, 0);
}


var min, sec, ms;
function render() {
    var value = paused ? offset : Date.now() + offset;

    ms = format(value, 1, 1000, 3);
    sec = format(value, 1000, 60, 2);
    min = format(value, 60000, 60, 2);
  
    if(!paused) {
        requestAnimationFrame(render);
    }
}

Thank you!

about 4 years ago · Juan Pablo Isaza
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