Note that there are some explanatory texts on larger screens.

plurals
  1. POSynchronization of two timers (setInterval)
    primarykey
    data
    text
    <p>I'm working in an script which contains a function that needs to be called at every 10 minutes. Also, to inform the user of how many time is left before reloading of the function (via AJAX, but this is not relevant now), I put a little regressive timer.</p> <p>This is the main structure:</p> <pre><code>$(document).ready(function () { // Test's function function loadDate() { var myDate = new Date(); $("#dateload").html(myDate); }; // Startup Variables countermin = 10; // 10 minutes countersec = 60; minpass = 0; secpass = 0 // Showing info before timer. $("#reloadtime").html("Function will be reloaded in " + countermin + "m&lt;b&gt;" + (60 - countersec) + "&lt;/b&gt;s&lt;br/&gt;(countersec's value: " + countersec + " - secpass' value: " + secpass + ")"); $("#timescalled").text("The date function has been called " + minpass + " times after page's load."); loadDate(); // FIRST setInterval // It's our timer. intvl1 = setInterval(function () { if (countersec++ == 60) { countermin--; countersec = 1; } if (countermin &lt; 0) { countermin = 9; countersec = 1; secpass = 0; } secpass++; $("#reloadtime").html("Function will be reloaded in " + countermin + "m&lt;b&gt;" + (60 - countersec) + "&lt;/b&gt;s&lt;br/&gt;(countersec's value: " + countersec + " - secpass' value: " + secpass + ")"); }, 1000); // SECOND setInterval // Counting 10 minutes to execute the function again (and again...). intvl2 = setInterval(function () { minpass++; $("#minpass").text("The date function has been called " + minpass + " times after page's load."); loadDate(); }, 600000); }); </code></pre> <p>My problem is: both timers are not synchronized. The <code>intvl2</code> is executing the function and going back before the timer (<code>intvl1</code>) reaches 0. The error is about 20 seconds, increasing after each 10 minutes.</p> <p>If you compare with the time printed on beginning, around 6, 7 minutes of execution you can see difference with in the times, when comparing with your PC's clock.</p> <p>How can I get them synchronized?</p> <p>You can check <a href="http://jsfiddle.net/ZxrX8/" rel="nofollow" title="Click here">this fiddle</a>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload