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 Date.now() to get the number of milliseconds elapsed since January 1, 1970. Here's an example code snippet:
var tsDepart = Date.now(); var secondes = 0; var timer = setInterval(function(){ secondes = Math.round((Date.now()-tsDepart)/1000); },1000);
In this code: We first record the value of Date.now() 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 Date.now() 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