/**
* Schedules a one-off script execution for given dates.
* Supports older browsers (IE11+).
*
* @param {Array<Date>} dates An array of Date objects representing the execution times.
* @param {Function} script The function to execute.
* @param {boolean} [immediate=false] Whether to execute the script immediately.
*/
function scheduleOneOffScript(dates, script, immediate = false) {
if (!Array.isArray(dates)) {
console.error("Dates must be an array.");
return;
}
if (typeof script !== 'function') {
console.error("Script must be a function.");
return;
}
for (let i = 0; i < dates.length; i++) {
const date = dates[i];
if (!(date instanceof Date) || isNaN(date)) {
console.error(`Invalid date at index ${i}: ${date}`);
continue; // Skip to the next date
}
const delay = immediate ? 0 : date.getTime() - Date.now(); // Calculate delay
if (delay <= 0) {
// Execute immediately if the date is in the past
script();
continue;
}
// Use setTimeout for scheduling - works in older browsers
setTimeout(() => {
script();
}, delay);
}
}
Add your comment