P5js instance mode running sketches after removing them from DOM

Hello, I am making a sketch browser for myself using p5 instance mode.

The sketches seem to continue running after removing them from the DOM. which results in my CPU getting pinned…

relevant code is here:

const loadSketch = ({ sketch, name }, params) => {
  console.log('loading sketch', name, params)

  if (canvas.childNodes[0]) canvas.removeChild(canvas.childNodes[0])

  new p5(p => sketch(p, params), 'canvas')
}

the sketches are just basic stuff of animating a bunch of circles on the screen. when i hit this function, it removes the old canvas from the dom and replaces it with the new one. it seems p5 still runs in the BG

1 Like

Although the app below doesn’t work anymore b/c the remote JSON file it depends on got removed, it’s got some tricks on its function p5RemoveHack():

However, even back then, I didn’t do enough tests to check whether the “hack” actually worked:
p5js.org/reference/#/p5/remove

function p5RemoveHack() {
  if (window.p5 && p5.instance) {
    p5.instance.remove();
    p5.instance = window.setup = window.draw = null;
  } else {
    const canv = document.querySelector('canvas');
    canv && canv.remove();
  }
}
1 Like