开发者

Issue passing the correct item to an other function with setTimeout

Her开发者_如何学Goe's my problem:

var slide;
$$('#slides li').each(function(i, n) {
    slide = i;
    setTimeout("initiateSlide()",n * 500)                     
});
function initiateSlide(){
    i = slide;
    alert(i); // pretty much alerts the last one 5 times
}

I expect to initiateSlide() with 5 different slides, instead I only get the last one 5 times.


Your problem is that the global variable (slide) that you are referencing in the initiateSlide() function is set to the last one by the time the function runs. You probably want to use closures to maintain the state of the variable. Like this:

$$('#slides li').each(function(i, n) {
    setTimeout(function() { initiateSlide(i); }, n * 500)
});
function initiateSlide(i){
    alert(i);
}

Note - This also removes the need for the global entirely


I recommend you to get rid of the global variables and pass each slide within the loop as an argument to your initiateSlide function:

$$('#slides li').each(function(slide, n) {
  setTimeout(function () {
    initiateSlide(slide);
  }, n * 500)                     
});

function initiateSlide(slide){
  alert(slide);
}​

In your example, the each loop ended before any setTimeout callback was executed, your initiateSlide function was being invoked using the last iterated element.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜