【问题标题】:Calling javascript multiple times causes setInterval to never be cleared多次调用 javascript 导致 setInterval 永远不会被清除
【发布时间】:2016-03-19 17:59:31
【问题描述】:

我正在将图像加载到 DOM 中

加载图像集和间隔的函数,并在执行另一个更改图像颜色的函数之前检查要完全加载的图像。

当文档加载时,我执行了 4 次这个函数(4 个不同的图像),这导致间隔永远不会在至少一个图像上被清除,有时是多个。

功能:

function setCloth(clothImg, prefix){
    $('#'+prefix+'_cloth_div').html('<img class="" id="'+prefix+'_clothImg" src="/figures/'+clothImg+'" />');
    cloth = prefix+'Cloth';
    imageSource[cloth] = '/figures/'+clothImg;

    checkClothInterval = setInterval(function(){
        if (document.getElementById(prefix+"_clothImg").complete){
              console.log('skin image complete');
              changeCloth(prefix, 'Cloth', '#ffffff');
              //====================================================
              //somehow this is not reached on a couple of the image loads
              //====================================================
              clearInterval(checkClothInterval);
          }else{
              console.log('skin image not complete');
          }
    }, 100);

}

它是变量范围还是什么?

【问题讨论】:

  • 对局部变量使用 var 关键字。

标签: javascript scope callback setinterval


【解决方案1】:

是变量作用域还是什么?

是的,您没有使用var 来声明您的变量,因此它们都是全局的,并且您只有一个checkClothInterval(全局)而不是每个间隔一个。每次声明变量时使用var:

function setCloth(clothImg, prefix){
    $('#'+prefix+'_cloth_div').html('<img class="" id="'+prefix+'_clothImg" src="/figures/'+clothImg+'" />');
    var cloth = prefix+'Cloth';
    imageSource[cloth] = '/figures/'+clothImg;

    var checkClothInterval = setInterval(function(){
        if (document.getElementById(prefix+"_clothImg").complete){
              console.log('skin image complete');
              changeCloth(prefix, 'Cloth', '#ffffff');
              clearInterval(checkClothInterval);
          }else{
              console.log('skin image not complete');
          }
    }, 100);

}

【讨论】:

  • 哇.. 一直以来我都认为前面的 var 使它成为全球性的.. 直到!谢谢
  • @silversunhunter 啊,你搞反了。 var 使其成为当前执​​行上下文的本地;如果没有var,新变量是隐式全局的。不客气。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-27
  • 2013-10-12
  • 2012-03-27
  • 2013-08-29
  • 2013-11-03
  • 1970-01-01
相关资源
最近更新 更多