多次调用 javascript 导致 setInterval 永远不会被清除
Calling javascript multiple times causes setInterval to never be cleared
我正在将图像加载到 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);
}
是可变作用域还是什么?
Is it variable scope or something?
是的,您没有使用 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);
}
我正在将图像加载到 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);
}
是可变作用域还是什么?
Is it variable scope or something?
是的,您没有使用 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);
}