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

256
Views
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
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!