【发布时间】:2017-11-13 22:32:48
【问题描述】:
我正在尝试使以下脚本正常工作,但是当它进入 continueAnimation 函数时,它不会更新 cPreloaderTimeout 变量,而是在“未捕获 RangeError:超出最大调用堆栈大小”中运行。
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 变量设置不正确。
【问题讨论】:
-
因为你没有正确使用
setTimeout。从setTimeout(this.continueAnimation(), ...)中删除()并阅读有关setTimeout的更多信息。 -
注意:当您修复
setTimeout问题时,您将陷入thisissue。
标签: javascript object methods stack-overflow