繁体   English   中英

Javascript setTimeout范围引用错误的变量

[英]Javascript setTimeout scope referencing wrong variables

我编写了一个小功能来遍历子画面。 在函数中,我有一个settimeout,它在帧之间循环。 在最后一帧,超时被清除,计数器设置为零-并且动画再次开始。

这对于一个动画效果很好,但是当我尝试调用许多动画时,它们都开始但无法循环播放,除了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参考。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM