javascript - Set an interval for every 12 hours -
i need function run , rerun @ 12pm , 12am. i'm using vuejs if has influence.
fetch_datetime() { axios.get('/api/core/datetime').then((response) => { this.datetime = response.data; this.set_interval(); }); }, set_interval() { var current_date = new date(); var hours = current_date.gethours(); var minutes = current_date.getminutes(); var seconds = current_date.getseconds(); if(hours == 12 && minutes == 0 && seconds == 0 || hours == 0 && minutes == 0 && seconds == 0) { this.fetch_datetime(); } else { if(hours >= 12) { settimeout(this.fetch_datetime, (1000 * (60 - seconds) * (60 - minutes)) + (1000 * 60 * (24 - hours - 1) * 60)); } else { settimeout(this.fetch_datetime, (1000 * (60 - seconds) * (60 - minutes)) + (1000 * 60 * (12 - hours - 1) * 60)); } }
however isn't working expected , function runs , runs multiple times on hour.
here simple function can want. should fit use case (refresh after minutes) don't expect resilient on browser changes.
// takes array of hours number , function execute function executeonhours(hours, callback) { callback(); // first, execute once let = new date(); const hourswithtoogle = hours.map(h => { return { value: h, executedtoday: now.gethours() === h // don't run if on given hour } }); setinterval(() => { = 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 boolean on next hour } }); if (triggers.length) callback(); // trigger action if hours match }, 30000); // fix precision check, here 30s } executeonhours([0, 12], function() { console.log('something done'); });
if looking far more robust solution, can use later.js, claims work on browser , offer full featured cron interface, @ cost of bundle size.
Comments
Post a Comment