2010-12-02 24 views
0
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 animateOff = 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); 
    } 
} 

我試圖通過切換他們src的「開」和「關」圖像之間的動畫這3張照片。我不希望這是'順序'。也就是說,我不想看到第一個圖像變化,然後是第二個,然後是第三個。有一些問題,我的非攔截JavaScript

我正在使用setTimeout來完成此操作。那麼,我試圖...

首先,我遇到的問題是在for loop內的setTimeout

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); 
} 

我不知道內point不匹配外point:/

另外,我想知道,如果這種方法,好了,傻了。這些嵌套函數調用是否會不斷建立到堆棧上並最終導致我用盡RAM?有沒有更好的方法來解決這個問題?

回答

0

由於閉包的工作原因,這不起作用。

我會做這樣的:

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); 
} 

而且這不是從一個堆棧指針的問題。每次執行超時時,它都在新的調用堆棧中。這就是爲什麼你需要_thissetTimeout()沒有暫停該線程,然後恢復它執行新鮮的功能。