开发者

Having some issues with my non-blocking Javascript

this.plotted = [jQuery('#img1'), jQuery('#img2'), jQuery('#img3')];

Blah.prototype.animate = function()
{
    if (!this.plotted.length)
        throw 'Blah::animate - No points have been plotted';

    // fix the scope
    var _this = this;

    var animateOn = function(image)
    {
        image.attr('src', _this.options.pointActive);

        setTimeout(function() { animateOff(point); }, 700);
    }

    var anima开发者_开发百科teOff = function(image)
    {
        image.attr('src', _this.options.pointDefault);

        setTimeout(function() { animateOn(point); }, 700);
    }

    for (var i = 0; i < this.plotted.length; i++)
    {
        var point = this.plotted[i];

        setTimeout(function() { animateOn(point); }, 700);
    }
}

I'm trying to animate these 3 images by switching their src between an 'on' and 'off' image. I don't want this to be 'sequential'. Ie, I don't want to see the first image change, then the second and then the third.

I'm using setTimeout to accomplish this. Well, I'm trying to...

Firstly, the problem I'm having is with the setTimeout inside the for loop.

for (var i = 0; i < this.plotted.length; i++)
{
    var point = this.plotted[i];

    console.log(point); // this correctly shows each image point

    setTimeout(function()
    {
        console.log(point); // this shows the same, first, point
        animateOn(point);
    }, 700);
}

I have no idea what the inner point isn't matching the outer point :/

Also, I would like to know if this method is, well, stupid. Will these nested function calls continually build onto the stack and eventually cause me to run out of RAM? Is there a better way to approach this?


This doesn't work because of how closures work.

I'd do it like this:

var makeAnimateStarter = function(point) {
  return function() {
     animateOn(point);
  };
};

for (var i = 0; i < this.plotted.length; i++)
{
  var point = this.plotted[i];

  setTimeout(makeAnimateStarter(point), 700);
}

And it's not a problem from a stack point of view. Every time a timeout is executed, it's in a new call stack. That's why you require _this. setTimeout() is not suspending the thread at that point and then resuming it's executing the function fresh.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜