1. /**
  2. * Validates time values against a given timeout.
  3. *
  4. * @param {function} validateTime - Function to validate a time value. Should return true if valid, false otherwise.
  5. * @param {number} timeout - Timeout in milliseconds.
  6. * @param {function} timeValueProvider - Function to get the time value. Should return a Date object or a string that can be parsed to a Date object.
  7. * @returns {Promise<void>} - A promise that resolves if the time is valid within the timeout, rejects if not.
  8. */
  9. async function validateTimeWithTimeout(validateTime, timeout, timeValueProvider) {
  10. return new Promise((resolve, reject) => {
  11. const startTime = Date.now();
  12. // Function to check the time periodically
  13. const checkTime = () => {
  14. const currentTime = Date.now();
  15. const elapsed = currentTime - startTime;
  16. if (elapsed > timeout) {
  17. reject(new Error("Timeout exceeded while validating time."));
  18. return;
  19. }
  20. try {
  21. const time = timeValueProvider(); //Get the time value
  22. if (validateTime(time)) {
  23. resolve();
  24. } else {
  25. //If not valid, check again after a short delay
  26. setTimeout(checkTime, 100);
  27. }
  28. } catch (error) {
  29. reject(new Error(`Error during validation: ${error.message}`));
  30. }
  31. };
  32. // Initial check
  33. checkTime();
  34. });
  35. }

Add your comment