Javascript 内存泄漏在动画期间将新图像加载到对象中

问题描述 投票:0回答:1

我有一种方法,可以在每次循环动画时用新图像更新对象,但会导致持续的内存泄漏,最终使动画的其余部分陷入停滞。方法大致是这样的:

  loadInstance(c) {
    let promise = new Promise((resolve, reject) => {
         //this is required because the new image is based on another image      
//"this.icon" which is loaded before the animation loop.
        if (this.icon !== false) {
          //create a new image:
          let img = new Image();
          img.src = "testImg.png";
           
          //load the image
          img.onload = () => {
            //initial image is set as false, check that this is not so
            if (this.image !== false) {
              //sets the image's onload and src to null
              this.image.src = "";
              this.image.onload = null;
            }
            //sets the new image to the object
            this.image = img;
            resolve();
          };
        }

    }); //end promise
    return promise;
  }

自然地,我认为泄漏是由于内存中仍在引用新图像,因此我确保在更新下一个图像之前将每个先前图像清空。这确实有很大帮助,但我似乎仍然从与此方法相关的其他东西中不断泄漏。我也清空了上一张图片的onload方法,但仍然没有变化。有什么想法吗?

javascript animation memory-leaks html5-canvas
1个回答
0
投票

如果一个承诺永远无法解决,它将无限期地挂在内存中。 如果其中有 if 语句,请确保在每条路径中都解决或拒绝。

function loadInstance(c) {
  return new Promise((resolve, reject) => {
    if (!this.icon) {
      resolve();
      return;
    }
    let img = new Image();
    img.src = 'testImg.png';
    img.onload = () => {
      this.image = img;
      resolve();
    };
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.