1. /**
  2. * Schedules a one-off script execution for given dates.
  3. * Supports older browsers (IE11+).
  4. *
  5. * @param {Array<Date>} dates An array of Date objects representing the execution times.
  6. * @param {Function} script The function to execute.
  7. * @param {boolean} [immediate=false] Whether to execute the script immediately.
  8. */
  9. function scheduleOneOffScript(dates, script, immediate = false) {
  10. if (!Array.isArray(dates)) {
  11. console.error("Dates must be an array.");
  12. return;
  13. }
  14. if (typeof script !== 'function') {
  15. console.error("Script must be a function.");
  16. return;
  17. }
  18. for (let i = 0; i < dates.length; i++) {
  19. const date = dates[i];
  20. if (!(date instanceof Date) || isNaN(date)) {
  21. console.error(`Invalid date at index ${i}: ${date}`);
  22. continue; // Skip to the next date
  23. }
  24. const delay = immediate ? 0 : date.getTime() - Date.now(); // Calculate delay
  25. if (delay <= 0) {
  26. // Execute immediately if the date is in the past
  27. script();
  28. continue;
  29. }
  30. // Use setTimeout for scheduling - works in older browsers
  31. setTimeout(() => {
  32. script();
  33. }, delay);
  34. }
  35. }

Add your comment