Javascript setTimeout 范围引用错误的变量

标签 javascript scope

我编写了一个小函数来循环遍历 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/

相关文章:

javascript - 如何使用javascript点击链接

javascript - 在 heroku 中部署一个 html 文件网站

javascript - 如何在 JavaScript 数组中存储 HTML 标题

python - 如何访问类范围内的 "self"?

JavaScript 范围 : timer referencing arbitrary new object

javascript - 获取缺少错误处理程序套接字消息,无法使用 Node.js 和 Socket.io 读取未定义的属性 'timerID'

javascript - 嵌套在 ngIf 中时,异步管道订阅无法正常工作

javascript - 有没有办法用 block 范围进行多重赋值和初始化?

perl - 为什么 perl 不关心我是否在限制条件下声明了我的变量?

php - 类声明的范围