/**
* Validates time values against a given timeout.
*
* @param {function} validateTime - Function to validate a time value. Should return true if valid, false otherwise.
* @param {number} timeout - Timeout in milliseconds.
* @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.
* @returns {Promise<void>} - A promise that resolves if the time is valid within the timeout, rejects if not.
*/
async function validateTimeWithTimeout(validateTime, timeout, timeValueProvider) {
return new Promise((resolve, reject) => {
const startTime = Date.now();
// Function to check the time periodically
const checkTime = () => {
const currentTime = Date.now();
const elapsed = currentTime - startTime;
if (elapsed > timeout) {
reject(new Error("Timeout exceeded while validating time."));
return;
}
try {
const time = timeValueProvider(); //Get the time value
if (validateTime(time)) {
resolve();
} else {
//If not valid, check again after a short delay
setTimeout(checkTime, 100);
}
} catch (error) {
reject(new Error(`Error during validation: ${error.message}`));
}
};
// Initial check
checkTime();
});
}
Add your comment