0👍
Here is a very simple function that can do what you want. It should fit your use case (refresh after some minutes) but don’t expect it to be very resilient on browser changes.
// Takes an array of hours as number and a function to execute
function executeOnHours(hours, callback) {
callback(); // First, execute once
let now = new Date();
const hoursWithToogle = hours.map(h => {
return {
value: h,
executedToday: now.getHours() === h // Don't run now if already on the given hour
}
});
setInterval(() => {
now = new Date();
const triggers = hoursWithToogle.filter(h => {
if (!h.executedToday && h.value === now.getHours()) {
return h.executedToday = true;
} else if (h.value !== now.getHours()) {
h.executedToday = false; // Clean the boolean on the next hour
}
});
if (triggers.length) callback(); // Trigger the action if some hours match
}, 30000); // Fix a precision for the check, here 30s
}
executeOnHours([0, 12], function() {
console.log('Something is done');
});
If you are looking for a far more robust solution, you can also use later.js, that claims to work on browser and offer a full featured cron interface, at the cost of bundle size.
0👍
I would at first calculate the distance to the next 12 am/pm and after the first run you can add 12 hours in every call or create an interval.
To get the distance to the first run you can use difference of Date.now
and the moment to run:
var n = new Date()
if(n.getHours()>=12){
n.setHours(24);
}else{
n.setHours(12);
}
After this set all smaller units than hour to zero.
After initial call:
setInterval(this.fetch_datetime, 12 * 60 * 60 * 1e3)
There is also a vue plugin which provides help for intervals and callbacks https://www.npmjs.com/package/vue-interval
You should also have in mind that setTimeout and setInterval are not absolutely correct. They may get triggered a few millisecounds to early or to late. So calculating the difference to the next execution moment can trigger the function double.