JavaScript: is this timer reliable?

Today I met the world of Web Workers in JavaScript. It made me think about timers. I used an ugly way for programming timers like this.

var time = -1; function timerTick() { time++; setTimeout("timerTick()",1000); $("#timeI").html(time); } 

I know that this can be improved by keeping the timer running date, but I have never been a fan of this.

Now I came up with a method using Web Workers, I did a little test and found it much more reliable. Since I am not a JavaScript expert, I would like to know if this function works correctly or what problems it might get in advance.

My JavaScript code (note that I'm using jQuery):

 $(function() { //-- Timer using web worker. var worker = new Worker('scripts/task.js'); //External script worker.onmessage = function(event) { //Method called by external script $("#timeR").html(event.data) }; }; 

External script ('scripts / task.js'):

 var time = -1; function timerTick() { time++; setTimeout("timerTick()",1000); postMessage(time); } timerTick(); 

You can also watch a live demo on my site .

+4
source share
2 answers

If you are trying to reliably display the ticking seconds, then the only reliable way to do this is to get the current time at the beginning and use the timer ONLY to refresh the screen. At each tick, you get the current time, calculate the actual elapsed seconds and display it. Neither setTimeout() nor setInterval() are guaranteed or can be used to accurately calculate time.

You can do it as follows:

 var start = +(new Date); setInterval(function() { var now = +(new Date); document.getElementById("time").innerHTML = Math.round((now - start)/1000); }, 1000); 

If the browser is busy and the timers have spaced intervals, you may receive a slightly irregular update on the screen, but the elapsed time will remain accurate when the screen is updated. Your method is susceptible to accumulating errors in the past tense.

You can see this work here: http://jsfiddle.net/jfriend00/Gfwze/

+9
source

The most accurate timer is a comparison of two time stamps. You can increase the accuracy of your timer by updating more often (for example, every 100 ms). I prefer to use setInterval() over setTimeout() .

0
source

Source: https://habr.com/ru/post/1383979/


All Articles