Pomodoro Clock- InAccuracy of setInterval when setting timersssss

For those working on and/or completed the pomodoro clocks - Are there solution to this inaccuracy of the timer methods??

http://codepen.io/docwali777/pen/LRaPXz

Just found this solution. https://www.sitepoint.com/creating-accurate-timers-in-javascript/

The way to handle it is not to use set interval for anything other than updating the display. The best way is when the user clicks (start) capture number of millisecond left. use a variable for Date.now() start time. then use a Date.now() to find the time now and subtract and make a pretty display.

This uncouples the simulation from the display and makes it more accurate. by a few dozen milliseconds.
For example:

  var timeLeft = 25 * 60 * 1000;
  var timeStart = 0;
  var setInterTimer;

$('#start').click(function(){
  timeStart = Date.now(); //captures current time in milliseconds since like 1971
  setInterTime = setInterval(function(){
    var minsLeft = (Date.now() - timeStart) / 1000 / 60;
    var secsLeft = ((Date.now() - timeStart) / 1000 % 60).toString().slice(0, (num.indexOf("."))+2)
    $('#timeLeft').html(minsLeft + " : " + secsLeft);
  } ,500)
});

Now you know how to decouple the simulation from the display that you can add pause and reset and the time adjustments. :slight_smile: No IDE/Test Editor - I just typed this stright in so there may and should be bugs.

2 Likes

I appreciate your input … will definitely check this out