Skip to content

Instantly share code, notes, and snippets.

@TravisMullen
Last active February 17, 2016 05:05
Show Gist options
  • Save TravisMullen/65a389fb38fa7ef632e2 to your computer and use it in GitHub Desktop.
Save TravisMullen/65a389fb38fa7ef632e2 to your computer and use it in GitHub Desktop.
Execute Function on specified time.
/* ============================================= *
queue to fire today ╭∩╮(︶︿︶)╭∩╮
* ============================================= */
function triggerOnTime(cb, hour, minute, pm) {
var config = {
// set to noon as default
hour: hour || 12,
min: minute || 0,
sec: 59,
ms: 100
},
// get current time
__NOW__ = new Date(),
targetTime,
triggerTime,
tMinus;
if (typeof cb !== 'function') {
// not valid function to set
return;
}
// add for Post Meridiem
if (pm) {
config.hour += 12; // add 12 hours for a pm time
if (config.hour === 24) {
config.hour = 0;
}
}
// calc trigger time
targetTime = new Date(__NOW__.getFullYear(), __NOW__.getMonth(), __NOW__.getDate(), config.hour, config.min, 0, 0);
// get a head of race!
// roll back 900 ms
--config.min;
if (config.min < 0) {
config.min = 59;
--config.hour;
}
// calc augmented trigger time
triggerTime = new Date(__NOW__.getFullYear(), __NOW__.getMonth(), __NOW__.getDate(), config.hour, config.min, config.sec, config.ms);
// get countdown time
tMinus = triggerTime - __NOW__;
if (tMinus < 0) {
tMinus += 86400000; // it's after the time, try tomorrow.
}
setTimeout(function() {
cb({
'time': targetTime,
'countdown': tMinus
});
}, tMinus);
return tMinus;
}
// example of use * ---- >
// time as 24:00 or use 'pm' flag
// 4:20pm // all below are valid
// triggerOnTime(fn(){}, 6, 20);
// triggerOnTime(fn(){}, 4, 20, true);
// triggerOnTime(fn(){}, 4, 20, 'pm');
triggerOnTime(function(info) {
// `info.time` and `info.countdown` if you need'em
var msg = 'The time is: ' + info.time + '\r';
info.countdown = info.countdown / 1000;
msg += 'This was initiated ' + info.countdown + ' seconds ago.';
alert(msg);
}, 4, 20, 'pm');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment