hv-pul / hv-boilerpate-rfcs

Collecting ideas on how to take the hv-boilerplate to the next level
0 stars 0 forks source link

Automatically clearing timeouts & intervals #1

Open hv-pul opened 2 years ago

hv-pul commented 2 years ago

Summary

Similar to how we clear all event listeners when a Module is destroyed, we should clear up after timeouts and intervals.

Basic example

Do this in your module:

init() {
    this.setTimeout(…);
}

and the timer will be cleared even if the Module is destroyed before the timeout runs out.

Motivation

Forgetting to clear a timeout is common. This would add a bit of security against memory leaks and allow a convenient syntax for simple timeouts/intervals.

Detailed design

I suggest adding straight-forward wrappers around window.setTimeout and window.setInterval that would also return a timer ID to manually clear the timer, but that would add the timer ID to a set that would be automatically cleared when the module is destroyed.

Unlike on / off for Event-Listeners, I think we should stick with the original naming because the function signature would be identical to the browser builtins.

In BaseModule.js:

init() {
    this._timeouts = new Set();
    this._intervals = new Set();
}

setTimeout(callback, duration) {
    this._timeouts.add(window.setTimeout(callback, duration));
}

clearTimeout(handle) {
    this._timeouts.delete(handle);
    window.clearTimeout(handle);
}

clearTimers() {
    this._timeouts.forEach(window.clearTimeout)
    this._intervals.forEach(window.clearInterval)
}

destroy() {
    this.clearTimers();
}

Drawbacks

It could be confusing for developers when to use this.setTimeout instead of window.setTimeout (basically this.setTimeout should always be preferred). There is not big cost to the classical usage though.

betabong commented 2 years ago

We do that in Edelweiss – I'm gonna add it to the Boilerplate, because that kind of stuff (good clean destroy) makes too much sense.

hv-pul commented 1 year ago

@betabong Did you have time for that already? I could do it today.