Tobia
Tobia

Reputation: 9506

Javascript timer performance

i saw that sometimes javascript timers have a bit of lag. I would like to know if you think that it is better to have more timers with different timings or just one.

For example, i need two timers, one for clock seconds refresh (every 1000 millis) and another one for some updates from server (every 3600 millis). Do you think that it is better to us only one timer (the more frequently) with somethig like:

if(dateObj.getSeconds()==0){
  //do update each minute
}

Maybe the answer is: it is the same... :-)

Thank you.

Upvotes: 0

Views: 1038

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Having two timers is a much better idea - more readable and easier to maintain.

If one piece of code runs intensively for few seconds the browser will most likely kill such a script. So don't expect lags being bigger than these few seconds. However typically this lag shouldn't be bigger than few tens if milliseconds.

If you need to know exactly when timer was scheduled and what is the lag, see this simple code snippet:

var scheduled = new Date().getTime() + 100;
setTimeout(function() {
  var lag = new Date().getTime() - scheduled;
  //...
}, 100);

lag variable in my case (Firefox) is always between -1 (!) and 1 millisecond.

Upvotes: 2

Related Questions