tags:

views:

27

answers:

2

In a javascript code I develop, some function should be called every 1 second. But to be sure that this operation takes place every 1 second, the following code is utilized:

setInterval(doIt, 500);
function doIt() {
    var now = (new Date()).getTime();
    if(lastUpdate + 1000 >= now) {
       /// code...
       lastUpdate = now;
    }
}

As far as I know setInterval(doIt, 1000) doesn't always mean that it's called every one second.

Is the above solution is a valid one? If not, what do you recommend?

A: 

well setInterval IS defined in milliseconds. so it means its called every X millisdconds. however the system can freeze or something like that! but theres no practical better solution, you approach is fine. if you really have an extensive javascript client application the results could stretch a little bit. a possible solution for that is to get the system time and have a counter in your function. then ever X executions you align with the system clock, calculate how many function calls you should have until now and speed up the interval or slow it down. this is as far as you can get to perfection. but it will be only a matter of milliseconds and probably not worth the effort. may i ask what you are developing?

Joe Hopfgartner
I'm developing a chat-like application where the duration is very critical. Besides the code above, in every 5 secs, the duration is updated by an Ajax call to the server to synchronize the time. But I want to lower the frequency of calling the server.
Zafer
i understand. the serverside synchronization is a very good idea. but isnt 5 secs a bit harsh? regarding the server-client delay? but i'm sorry im not aware of a better approach! i can almost definately say there isnt.
Joe Hopfgartner
how critical can this application be? :D who posts first gets 1000$? :D
Joe Hopfgartner
It's not that critical :).
Zafer
+1  A: 

You could use setTimeout instead of setInterval, and make dynamic adjustments each time your function is called. The idea is to set the timeout for a number of milliseconds sufficient to carry you to the next second boundary.

function timeoutFunc() {
  // do interesting things
  var time = new Date().getTime();
  setTimeout(timeoutFunc, 1000 - time % 1000);
}

You'd start it off with:

setTimeout(timeoutFunc, 1000 - new Date().getTime() % 1000);

Synchronizing with the server seems like a bad idea, because you have no way of knowing whether the client clock is synchronized to anything (like the NTP server network). If it's not, then you server synchronizations are going to make things look wrong at the client, because the client clock will always be what seems right.

Pointy
The serverside code doesn't synchronize the time, it synchronizes the duration past in the session.
Zafer