Using timer I am able to call a function every 1 minute but not the way I want, if now is 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 this? 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 });
You could set a time out based on the amount of time till 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()
You can start from something like that...
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();
})
;
Set the subscription interval to 1000 and check when seconds change to 0. Here is a simple solution to do exactly what you want with minimum changes in your original code:
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.
}
}
);
Here is a working plunk: DEMO
I have changed Faisal's solution and now it works ok, also it starts instantly and there is no problem with accumulating offset:
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
}
});
Try something like this, though, as @Hitmands stated, you'll never get full precision :
let date = new Date(), remainingSeconds = 60 - date.getSeconds(); function myFunc () { console.log(new Date()); } myFunc(); setTimeout(() => { myFunc(); setInterval(myFunc, 60000); }, remainingSeconds * 1000);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.