0

I'm developing a chronometer app in Tizen and I'm currently using the setInterval function to schedule the next time the text with the numbers will be updated:

   chrono : function() {
       SecondsChrono += 1;
   },
   setInterval(chrono(), 1000);

But when the device's screen is put on "sleep mode" the chronometer gets delayed. I want to know if anyone has experienced this and if you have some way to avoid it or if you have any advice for me to implement this chronometer in another way.

Kamila Brito
  • 198
  • 8

1 Answers1

1

You should use setInterval only to update the screen, to see how much time has ellapsed since the chronometer first started you should do something like this:

var SCREEN_UPDATE_REFRESH_RATE= 1000;
var startTime= (new Date()).getTime();
var updateScreen= function() {
    var currentTime= (new Date()).getTime();
    var timeEllapsed = currentTime - startTime; //this value is in milliseconds
    document.write("Ellapesed time in seconds: " timeEllapsed / 1000);
    setTimeout(updateScreen, SCREEN_UPDATE_REFRESH_RATE);
}
updateScreen();

It is better to use setTimeout in this case than setInterval. The difference between the two is that setInterval schedules the function to execute forever every X milliseconds while setTimeout schedules to execute once and then never again, in this case the function sets a new timeout that keeps the updating process forever. If your user system is overloaded various setInterval callbacks can be chained together which can freeze the user browser. See this for more information.

Hoffmann
  • 14,369
  • 16
  • 76
  • 91
  • Why exactly use `setTimeout` instead of `setInterval`? – Bergi Oct 06 '14 at 15:17
  • None of the reasons mentioned in that article really qualify here. Repeated `setTimeout`s are quite equivalent to `setInterval` - only one is simpler to use than the other. – Bergi Oct 06 '14 at 17:29
  • It turns out that none of this approaches can fix my problem, I'll have to implement my chronometer in C and see if it will work. All I know now is that setInterval and setInterval doesn't work for me. Thanks anyway, guys. – Kamila Brito Oct 07 '14 at 13:56