我写了一个小函数来循环一个精灵表。在函数中,我有一个循环遍历帧的settimeout。在最后一帧,超时被清除,计数器被设置为零 - 动画再次开始。
这适用于一个动画,但是当我尝试调用许多动画时 - 它们都开始但无法循环,除了designSprite,它非常愉快地循环。我最后称之为designSprite anim ....
所以我猜这个问题是由于当我调用函数的新函数时变量被覆盖 - setTimeOut引用新变量?我弄糊涂了自己。我试图修复它,但仍然失败。
谢谢, 罗布
// 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();
}
答案 0 :(得分:3)
setAnim
看起来没有被声明,这意味着它是一个全局变量。这意味着您对loopAnim
的所有呼叫都在使用并覆盖相同的计时器ID参考。