Implementing a delay between the current time and a specified time using TypeScript
About 225 wordsLess than 1 minute...
Abstract
Due to automation business requirements, the project reset time is not fixed. Therefore, a delay calculation function needs to be written in TypeScript to compute the delay between the current time and a specified date. This function can be used in scenarios such as alarms/timers.
Coding
TypeScript
/**
 * delay calculation
 * @notice  Sunday - Saturday [0, 1, 2, ..., 6]
 * @param target_hour
 * @param target_minute
 * @param days
 */
export const calc_delay = (target_hour: number, target_minute: number, days: number[]): number => {
  const now = new Date();
  const target = new Date(now);
  target.setHours(target_hour);
  target.setMinutes(target_minute);
  target.setSeconds(0);
  target.setMilliseconds(0);
  if (target < now) target.setDate(target.getDate() + 1);
  while (days.indexOf(target.getDay()) === -1) target.setDate(target.getDate() + 1);
  return (target.getTime() - now.getTime()) / 1000;
}; Powered by  Waline  v3.3.0