Javascript递归调用创建范围错误
我试图让以下脚本正常工作,但当它进入continueAnimation函数时,它没有更新cPreloaderTimeout变量,并且它在“uncaughtrangeerror:超过最大调用堆栈大小”中运行Javascript递归调用创建范围错误,javascript,object,methods,stack-overflow,Javascript,Object,Methods,Stack Overflow,我试图让以下脚本正常工作,但当它进入continueAnimation函数时,它没有更新cPreloaderTimeout变量,并且它在“uncaughtrangeerror:超过最大调用堆栈大小”中运行 var loadingIcon = { cSpeed : 8, cWidth : 64, cHeight : 32, cTotalFrames : 7, cFrameWidth : 64, cImageSrc : 'sprites.pn
var loadingIcon = {
cSpeed : 8,
cWidth : 64,
cHeight : 32,
cTotalFrames : 7,
cFrameWidth : 64,
cImageSrc : 'sprites.png',
cImageTimeout : false,
cIndex : 0,
cXpos : 0,
cPreloaderTimeout : false,
SECONDS_BETWEEN_FRAMES : 0,
startAnimation : function() {
document.getElementById('loaderImage').style.backgroundImage='url('+ this.cImageSrc+')';
document.getElementById('loaderImage').style.width=this.cWidth+'px';
document.getElementById('loaderImage').style.height=this.cHeight+'px';
//FPS = Math.round(100/(maxSpeed+2-speed));
FPS = Math.round(100/this.cSpeed);
SECONDS_BETWEEN_FRAMES = 1 / FPS;
this.cPreloaderTimeout = setTimeout( this.continueAnimation(), SECONDS_BETWEEN_FRAMES/1000);
},
continueAnimation : function() {
this.cXpos += this.cFrameWidth;
//increase the index so we know which frame of our animation we are currently on
this.cIndex += 1;
//if our cIndex is higher than our total number of frames, we're at the end and should restart
if (this.cIndex >= this.cTotalFrames) {
this.cXpos =0;
this.cIndex=0;
}
if(document.getElementById('loaderImage'))
document.getElementById('loaderImage').style.backgroundPosition=(-this.cXpos)+'px 0';
this.cPreloaderTimeout = setTimeout(this.continueAnimation(), SECONDS_BETWEEN_FRAMES*1000);
},
stopAnimation : function(){//stops animation
clearTimeout( this.cPreloaderTimeout );
this.cPreloaderTimeout = false;
}
}
jQuery( document ).ready(function() {
jQuery( document ).on("click", "#test", function(){
var loader = loadingIcon;
loader.startAnimation();
setTimeout( loader.stopAnimation(), 3000);
});
});
起初它是一个普通的javascript脚本,但我正试图从中生成一个对象,以便可以重复使用,同时多次使用。现在的问题是,在触发startAnimation或continueAnimation时,cPreloaderTimeout变量设置不正确。您有几个问题 首先,您的cPreloaderTimeout不会像您想象的那样设置,因为您不会创建带有原型的对象,因此该函数中的作用域将是函数本身,而不是对象 其次,setTimeout接受一个函数,但您在尝试使用它时调用了该函数,因此发送给setTimeout的值将是函数的结果,而不是函数本身 请考虑以下格式:
function LoadIcon() {
this.cSpeed = 8;
// All your other properties
}
LoadIcon.prototype.startAnimation = function() {
// your startAnimation function, concluding with
this.preloaderTimeout = setTimeout(this.continueAnimation.bind(this), SECONDS_BETWEEN_FRAMES/1000);
}
// the rest of the methods built the same way
//then, your calling code would look like:
var loadIcon = new LoadIcon();
loadIcon.startAnimation();
编辑
我更新了setTimeout调用,因为我忘记了在回调触发时绑定到它以进行正确的作用域 因为您没有正确使用setTimeout。从setTimeoutthis.continueAnimation中删除。。。并阅读有关setTimeout的更多信息。注意:当您解决setTimeout问题时,您将陷入。我已经尝试了该格式,但在continueAnimation中,我不能使用“this”,因为此处不是LoadIcon,而是它的Window@MartijnBastiaansen对,对不起。这个问题现在已经解决了,请再看一看。