A timer that will not reset when updated

EDIT: How do I pass a parameter when calling Clock.start () so that I can change the value of totalSeconds?

I have a counter whose value I associate with the identifier of the timer display, since there will be several lines of timers on the page, but only one will work for each user. I want to pass the value of the timer to find out which line the timer is that I need to extract, and then I convert it to seconds, and then finally I can assign that value to totalSeconds. Then maybe I can make it work the way I imagined everything.

WHAT I ALREADY WORK: I have a timer that does not show that it counts if I do not update. When the page loads mySQL PHP queries and calculates the elapsed time using TIMEDIFF (now (), time_log), where time_log is when the timer starts.

WHAT I LIKE TO ADD: what I want to do is use the js / jquery snippet below to get my TIMEDIFF and then use it as totalSeconds, so totalSeconds wont reset and continue counting from the TIMEDIFF value.

var Clock = { totalSeconds: 0, start: function () { var self = this; this.interval = setInterval(function () { self.totalSeconds += 1; var ctr; $(".icon-play").each(function(){ if( $(this).parent().hasClass('hide') ) ctr = ($(this).attr('id')).split('_'); }); $("#hour_" + ctr[1]).text(pad(Math.floor(self.totalSeconds/3600))); $("#min_" + ctr[1]).text(pad( Math.floor((self.totalSeconds/60)%60) )); $("#sec_" + ctr[1]).text(pad(parseInt(self.totalSeconds%60))); }, 1000); }, pause: function () { clearInterval(this.interval); delete this.interval; }, resume: function () { if (this.interval) this.start(); } }; 

For this script, loans for Mr. Speransky Danil. How to pause and resume the timer?

+4
source share
2 answers

Instead of recording the full seconds, you should instead record the start time and calculate the number of seconds between them and the start of the timer.

In addition, you already save your start time in the database, so you can initialize it when the page loads.

If you just count the seconds, you will lose time between page updates.

EDIT: You can create Clock.totalSeconds in the HTML output generated by PHP. I understand that you already have a working JS clock (with markup not posted above).

 <script type="text/javascript"> var Clock = {}; // your code above Clock.totalSeconds = <?php echo (int)$seconds; ?>; </script> 
+5
source

If you can target modern browsers, save totalSeconds in localStorage .
You can read totalSeconds back from localStorage

If you need to target older browsers, then using cookies to preserve the value is your best shot. I set a cookie date so that it expires pretty soon.

+1
source

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


All Articles