Call the function now and every 1 minute in a full minute?

Using the timer, I can call the function every 1 minute, but not the way I want, if now 10:35:21, the function should be called like this:

at 10:35:21
at 10:36:00
at 10:37:00
at 10:38:00
at 10:39:00
at 10:40:00
etc

How to do it? This is my current code:

let startTime = new Date(Math.ceil(new Date().getTime() / 60000) * 60000);
let source = Rx.Observable.timer(startTime, 60000).timeInterval().pluck('interval');


  this.Subscription = source
    .subscribe(data => { //code });
+4
source share
5 answers

You can set a timeout depending on the amount of time until the next minute.

var ONE_MINUTE_IN_MILLIS = 60000;

var runMe = function() {
  var now = new Date().getTime();
  console.log(new Date());
  setTimeout(runMe, getNextMinute(now));

}


var getNextMinute = function(now) {
  var timePassed = now % ONE_MINUTE_IN_MILLIS;
  return ONE_MINUTE_IN_MILLIS - timePassed;
}

runMe()
Run codeHide result
+2
source

You can start with something like this ...

Rx
  .Observable
  .create((observer) => {
    const oneMin = 60000;
    let index = 0;

    const iterate = () => window.setTimeout(iteration, (
      oneMin - (Date.now() % oneMin)
    ));

    function iteration() {
      observer.next(index++);

      return iterate();
    }

    iteration();
  })
;
+1
source

1000 , 0. , , , :

let startTime = new Date(Math.ceil(new Date().getTime() / 60000) * 60000);
let source = Observable.timer(startTime, 1000);
this.Subscription = source.subscribe(
    ticks => {
        if((ticks % 60) === 0) {
            console.log('Current Seconds is 0'); 
            // Perform your action here.
        }
    }
);

: DEMO

+1
source

I changed Faisal's solution, and now it works fine, it also starts instantly and there is no problem with bias accumulation:

  let startTime = new Date();
  this.Source = Rx.Observable.timer(startTime, 1000).timeInterval().pluck('interval');

  this.Subscription = this.Source
    .subscribe(data => {
      if (Math.floor(this.LastPing.getTime() / 60000) * 60000 != Math.floor(new Date().getTime() / 60000) * 60000) {
        this.LastPing = new Date();
        //rest of the code        
      }
    });
0
source

Try something similar, but as @Hitmands says , you will never get full accuracy:

let date = new Date(),
    remainingSeconds = 60 - date.getSeconds();

function myFunc () {
  console.log(new Date());
}

myFunc();

setTimeout(() => {  
  myFunc();
  setInterval(myFunc, 60000);
}, remainingSeconds * 1000);
Run codeHide result
-1
source

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


All Articles