gpt4 book ai didi

Javascript setTimeout 范围引用错误的变量

转载 作者:行者123 更新时间:2023-11-28 20:09:43 24 4
gpt4 key购买 nike

我编写了一个小函数来循环遍历 Sprite 表。在函数中,我有一个循环帧的设置超时。在最后一帧后,超时被清除,计数器设置为零 - 并且动画再次开始。

这对于一个动画效果很好,但是当我尝试调用许多动画时 - 它们都启动但无法循环,除了 designSprite 循环得非常愉快。我最后调用 designSprite 动画......

所以我猜测问题是由于当我调用函数的新实例时变量被覆盖 - 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();
}

最佳答案

setAnim 看起来没有声明,这意味着它是一个全局变量。这意味着对 loopAnim 的所有调用都使用并覆盖相同的计时器 ID 引用。

关于Javascript setTimeout 范围引用错误的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20103776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com