Avoiding slowdowns of a JavaScript counter on an inactive tab

If you're trying to create a Javascript counter that increments every second, you may notice that it works correctly when you're on the active tab but experiences slowness when the tab is not active. This can lead to a desynchronization between the counted seconds and real-time.

Here's a simple method to address this issue

You can use to get the number of milliseconds elapsed since January 1, 1970. Here's an example code snippet:

var tsDepart =;
var secondes = 0;

var timer = setInterval(function(){

	secondes = Math.round((;


In this code: We first record the value of in a variable called "tsDepart." Then, we create a function that will be executed every second using "setInterval()." We calculate the number of seconds elapsed since we recorded the "tsDepart" variable. To do this, we find the difference between the current and the starting time ("tsDepart"), divide the result by 1000 to get the result in seconds, and round the value using Math.round(). While this won't eliminate the slowdowns, it ensures that the counter's value remains accurate even if there are delays in execution due to inactive tabs or other factors.

Categories : Javascript

By Guillaume - 11/20/2016 at 07:15 pm

Shar this article :

Similar articles

Easily add a dual-slider to your HTML forms

When designing HTML forms, you may quickly find yourself limited by the basic form elements provided. For example, if you use sliders with the <input type="range"> element, they only allow the use of a single slider per element. However, there may be times when you need a field with two...