Javascript setTimeout作用域引用了错误的变量

Javascript setTimeout scope referencing wrong variables

本文关键字:错误 变量 引用 setTimeout 作用域 Javascript      更新时间:2023-09-26

我已经编写了一个小函数来循环遍历精灵表。在函数中,我有一个在帧中循环的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引用。