Okay, a couple of notes. If you're not required to run a script in the browser itself but simply run some JavaScript at specific intervals you should checkout some schedulers like cron and more specifically for JavaScript - node-cron.
A solution which revolves around checking "is it time, is it time,..." each second or so in a loop is a pretty bad way to do it.
- It is highly wasteful and poorly performant.
- It will block your script execution so you have to execute it in a separate process like a web worker.
The simplest way, without using any dependencies is to schedule your work manually using a combination of setTimeout
and setInterval
. Here is a pretty basic and unpolished solution which should get you going.
const msInSecond = 1000;
const msInMinute = 60 * msInSecond;
const msInHour = 60 * msInMinute;
const msInDay = 24 * msInHour;
const desiredTimeInHoursInUTC = 18; // fill out your desired hour in UTC!
const desiredTimeInMinutesInUTC = 30; // fill out your desired minutes in UTC!
const desiredTimeInSecondsInUTC = 0; // fill out your desired seconds in UTC!
const currentDate = new Date();
const controlDate = new Date(currentDate.getUTCFullYear(), currentDate.getUTCMonth(), currentDate.getUTCDate(), desiredTimeInHoursInUTC, desiredTimeInMinutesInUTC, desiredTimeInSecondsInUTC);
let desiredDate;
if (currentDate.getTime() <= controlDate.getTime()) {
desiredDate = controlDate;
}
else {
desiredDate = new Date(controlDate.getTime() + msInDay);
}
const msDelta = desiredDate.getTime() - currentDate.getTime();
setTimeout(setupInterval, msDelta);
function setupInterval() {
actualJob();
setInterval(actualJob, msInDay);
}
function actualJob() {
console.log('test');
}
In short, it calculates the difference between the current time and the next possible upcoming time slot for execution. Then, we use this time difference to execute the desired task and further schedule executions on every 24h after that.
You need to provide values for desiredTimeInHoursInUTC
, desiredTimeInMinutesInUTC
and desiredTimeInSecondsInUTC
. All of them should be in UTC (the normal difference between EST and UTC is -4
or in other words - (hour EST - hour UTC = -4
). You can (and actually should) improve this solution to handle timezones and the time difference calculations in general more elegantly.
A caveat here is that it won't handle daylight saving for you so you should keep that in mind. You can tackle this easily by using a dedicated library like moment.js. Also, the code is simple and in this version doesn't support cases like skipping specific days and such. You can always extend it to handle those, though.
Lastly, every time you restart the script, it will schedule your function execution times properly so you don't need to keep your tab open at all times. As an added benefit, the solution is quite performant as it doesn't do checks continuously if the time for execution has come but schedules everything in advance and doesn't do any more checks after that.