Is there an event for cleaning up cell JavaScript on cell re-execution or cell deletion?

If I’m rendering some JavaScript in Jupyter Notebook cell that schedules some code to run over and over with setInterval, adds a window-level event listener, etc., I’d like to be sure to cancel the setInterval, remove the event listener, etc. when the cell is re-executed or deleted.

Is there an API like this? Any advice on creating one, e.g. are there class names that are part of the API that I should build out this event around with a MutationObserver?

Edit: I wonder if this event should fire for collapsing cell outputs? I’ll say no for now.


I threw together some JavaScript that just notices two cases, cell reexecution and cell deletion. Any ideas for more times you might want resources used to render a cell be freed up?

I made a repo for this to clarify the question:

The repo includes an npm module that works as long as it has time to load before other JavaScript that uses it runs. I need to learn a bit more about writing JS in notebooks.