Javascript setTimeout作用域引用了错误的变量
Javascript setTimeout scope referencing wrong variables
我已经编写了一个小函数来循环遍历精灵表。在函数中,我有一个在帧中循环的settimeout。在最后一帧时,超时被清除,计数器被设置为零,动画再次开始。
这适用于一个动画,但当我尝试调用许多动画时,它们都开始了,但未能循环,除了designSprite,它循环得很愉快。我把designSprite动画称为最后一个。。。。
所以我猜这个问题是由于当我调用函数的一个新实例——引用新变量的setTimeOut时,变量被覆盖了??我弄糊涂了。我曾尝试过修复它,但一直失败。
谢谢,Rob
// Arrays to hold our sprite coordinates.
var animationSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
var mediaSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
var filmSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
var designSprite=[{"X":"-2","Y":"-2"},........ etc etc ];
// call the loopAnim function, passing in the sprite array, and id of the div
loopAnim(animationSprite ,'#animationFrame')
loopAnim(mediaSprite ,'#mediaFrame')
loopAnim(filmSprite ,'#filmFrame')
loopAnim(designSprite ,'#designFrame')
function loopAnim(sprite , frameID) {
var totalFrames = sprite.length; // count how many 'frames' are in our sprites array.
var count = 0; // set up a basic counter to count which frame we're on.
var theLoop = function(){
// Move the background position of our frame by reading the X & Y co-ordinates from the sprites array.
$(frameID).css("background-position" , sprite[count].X + "px " + sprite[count].Y + "px");
count++; // increment the frame by 1 on each loop
// if count is LESS than total number of frames, set a timeout to keep running the "theLoop" function
if (count < totalFrames){
setAnim = setTimeout(theLoop, 60);
// if count is greater than the total number of frames - clear our timeout. Reset the counter back to zero, and then run our loop function again
} else {
clearTimeout(setAnim);
count = 0;
theLoop();
}
}
theLoop();
}
setAnim
看起来像是未声明的,这意味着它是一个全局变量。这意味着所有对loopAnim
的调用都在使用和覆盖相同的计时器ID引用。
相关文章:
- jQuery变量错误
- 已定义变量出现未定义错误
- 可以'无法正确访问NODE_ENV环境变量,这是NODE.js的错误吗
- 使用eval()定义变量显示未定义的错误
- 变量类型错误
- react.js foreach变量错误
- 在JavaScript中引用未定义的变量时,如何避免出现错误
- 更新带有Javascript函数错误的变量
- Javascript中的LESS变量给出语法错误
- 如果JS会话变量为null,如何避免500内部服务器错误
- 未捕获的引用错误:变量未在单击函数上定义
- 范围变量返回长度错误
- 类型错误:变量未定义
- 字符串类型错误: 变量未定义
- 错误变量空间未定义原因
- 引用错误:变量未定义
- 引用错误变量未声明
- 错误变量没有定义,但在使用之前定义了
- 通过检查错误变量来停止提交表单
- 脚本错误:变量未定义