-3

Is it possible to start setInterval counter clock dependent instead of load dependent? Assuming that every computer has the minutes of the clock always at the same time.

If I open the page at 12:01 and I want a set interval of 2 minutes that always start from 12:00 (or any other hour but at :00 minutes). I want the event to fire at 12:02, 12:04 etc. no matter when I load the page or if it was open or not at 12:00.

The answer can be in jquery too.

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
Victordb
  • 519
  • 1
  • 11
  • 25
  • 1
    just take the actual time, and the delta of the next wanted slot and use it as delay time. – Nina Scholz Aug 28 '18 at 06:44
  • https://stackoverflow.com/a/29972322/965834 might help. – Jeto Aug 28 '18 at 06:44
  • @Nina Scholz can you please elaborate a bit. What is the delta of the next slot? – Victordb Aug 28 '18 at 10:03
  • delta is the diffrence between two values. in this case, you get the actual time and you know when you like to have the timeout. then you need the difference between both times and that is the delay time. – Nina Scholz Aug 28 '18 at 10:04
  • I don't know how can I get the wanted time given the fact that it is every 2 minutes I have (24hours*60)/2 posibilities. What am I supposed to compare the actual time with? – Victordb Aug 28 '18 at 10:10
  • you may have a look to the [reminder operator `%`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_()) (modulo). – Nina Scholz Aug 28 '18 at 10:56

1 Answers1

0

You could take the delta to the next wanted slot and adjust with it the timeout.

function out(k, v) {
    console.log(k.toString().padEnd(8), v.toString().padStart(15));
}

var time0 = new Date().getTime(),
    slot = 2 * 60 * 1000,
    time1 = Math.floor(time0 / slot + 1) * slot,
    delta = time1 - time0;

out('slot', slot);
out('delta', delta);
out('time0', time0);
out('time1', time1);

setTimeout(function () {
    var time2 = new Date;
    out('time2', time2.getTime());
    out('real', time2.getTime() - time0);
    console.log(time2.toISOString());
}, delta);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392