How to delete evaluated function in JavaScript

45 Views Asked by At

I have a script that looks like this:

arr.map(v => {
  v[0] = new Function(`
    try {
      if (${v[1]?.before}) {
        let func = ${v[0]};
        const rtn = func.call(this, this); // call function passed before deconstruction of tooltip
        func = undefined;
        
        this?.tooltip?.deconstruct(${misc?.fadeOut}); // deconstruction of tooltip
        return rtn;
      } else {
        this?.tooltip?.deconstruct(${misc?.fadeOut}); // deconstruction of tooltip

        let func = ${v[0]};
        const rtn = func.call(this, this); // call function passed after deconstruction of tooltip
        func = undefined;

        return rtn;
      }
    } catch(err) {
      return console.error(err); // TODO: remove in production
    }
  `);

  const bounded = v[0].bind(this); // bind tooltip to function so this.tooltip.deconstruction can be called
  v[0] = undefined;

  return [ bounded, v[1], v[2] ];
});

In the script, v[0] is always a function, v[1] gives information on what to do with the function, and variables v[2] and misc can be ignored for this question. This code is suppose to create a function for an eventListener, that when called, will destroy the tooltip that the function is connected to. However, every time this code executes, I get a new function that shows up in my loaded scripts in vscode, and I'm worried this may create a memory leak. Is there a way to delete these functions? Or should I writ the code differently?

Here is what my vscode debug looks like (this is from the live preview extension)

Image of all the eval functions after just a bit of running

If you need more information, I will send you it.

I've tried deleting the function using argument.callee, and tried deleting it when the event listener is removed, however they were all local scope. I'm expecting for the function to be removed from the loaded scripts.

0

There are 0 best solutions below