Tuesday, April 5, 2011

Issue passing the correct item to an other function with setTimeout

Here'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.

From stackoverflow
  • 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

    Mala : +1: Thanks! This solved the different problem I was having passing objects to setTimeout functions :)
  • 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 comments:

Post a Comment