The problem is you’re inserting the created canvas into another part of the page when you say e.g. .parent("randomDemo1")
. That prevents it from being cleaned up automatically, which is this line here in the code I posted:
p.draw = () => node.isConnected ? draw.apply(p, arguments) : p.remove();
I would avoid trying to “insert content elsewhere” and using global identifiers in the DOM, and stick to the pattern I suggested where the code is local to where it is displayed. Or, you could use the invalidation promise to clean up the canvases you are inserting elsewhere, but that’s probably more work.