Simple timer and setinterval

What's the best way to create a timer in JS?

I've used this so far:

var sec = 0;
setInterval(function (){sec +=1}, 1000);


I noticed that when I need milliseconds it slows down. On the browser tab tab, it stops completely.

var milisec = 0;
setInterval(function (){milisec +=1}, 1);


I'm looking for a better way to handle this, which will also keep working when the browser window changes.


source to share

2 answers

Based on @goleztrol's solution, I created an alternative solution specifically for my situation (it might not work for everyone).

I'm just asking the exact time when it is needed for this function to find out exactly which milliseconds have passed:

var start = new Date();
var msPassed = function() {
    var now = new Date();
    var ms = now.getTime() - start.getTime();
    return ms

msPassed(); //returns time passed in ms


I needed to position objects (on creation) depending on how long it took before they were created, so this is the perfect solution for my case. However, my original question asks for a perfect timer and it doesn't. Anyway, here it is for future reference.



With milliseconds, the timer resolution is not large enough. In most cases, the callback will not be called more often than about 50-250 times per second, even if you set the interval to 1ms. See Timer Resolution in Browsers (as Sani Hattunen mentions) for an explanation.

With 1000ms it will perform better. But still the timer will not run if the tab is inactive and can be delayed when the CPU is busy or a script is running on your page.

One solution is not to increment the counter, but to check how much time has passed since the previous call to the timer. This way, the time remains accurate even if the intervals have been delayed or suspended between them.

This snippet will remember the start date and at each timer interval, update the seconds and milliseconds to the difference between the current time and the start time.

var start = new Date();
var milliseconds = 0;
var seconds = 0;
    var now = new Date();
    milliseconds = now.getTime() - start.getTime();
    seconds = round(milliseconds / 1000);
}, 1000);


I set the interval to 1000 again. You can set it shorter, but it will cost more performance.

Related questions: How to make setInterval work when a tab is inactive in Chrome?



All Articles