Date as EventTarget

As everyone once in their life has used setInterval, setTimeout, or even worse requestAnimationFrame to show any timer on any screen, I wonder if we could add the EventTarget interface to the Date prototype, so that the following listeners could be added/removed/dispatched.

  • second, to be notified whenever the timer ticks a new second
  • minute, to be notified whenever the timer ticks a new minute
  • hour, to be notified whenever the timer ticks a new hour
  • day, to be notified whenever the timer ticks a new day
  • month, to be notified whenever the timer ticks a new month
  • year, to be notified whenever the timer ticks a new year

For the time being, I am leaving milliseconds out of the equation, as I think rAF would work same way, and I see it too greedy for any need.

The culprit is that as soon as any event is added via date.addEventListener(type, handler) the environment schedules a timer that triggers at required intervals, and drop it once removed.

I understand mixing WHATWG specs with TC39 might not be immediate/straightforward, but I think the whole JS community would benefit for most common time related tasks.

Best Regards

As alternative proposal, if that makes in any easier, a Timer global with a setInterval that accepts a callback and an optional string would work too, imho.

const eachSecond = Timer.setInterval(fn, 'second');
Timer.clearInterval(eachSecond);

The namespace Timer could be handy for future addictions, but a global scheduleInterval with a counter clearSchedule would work too, the whole idea here is to have any way to be notified per each second, minute, hour, day, month, or year, which is something not immediate with the current primitives.

Meanwhile, the clock-scheduler module landed as playground for timers pinned to the clock.

Same setTimeout and setInterval API, but the delay could be either milliseconds, on second, hour, minute, day, month, year, and milliseconds in these cases are always calculated as diff from now to the next clock tick.