Using Closures in Javascript to pass parameters to setTimeout()

For the home page of my site I wanted to cause certain divs to fadeIn using jQuery after varying amounts of time. In javascript we can use setTimeout() to schedule an arbitrary function call for some point in future. However the function works differently between Firefox and Internet Explorer (MSIE).

In FireFox, you would do this:

setTimeout(myFadeIn(), 1200, "id1");
setTimeout(myFadeIn(), 2700, "id2");
setTimeout(myFadeIn(), 3500, "id3");


Except, MSIE doesn’t like this. And in fact the additional parameter is not even part of the official javascript spec.

So how can we work around this ?

Closures. In the below example I use closures to pass an anonymous function to setTimeout() that contains in its “frozen in time local scope” the id of the div to fadeIn.

// Return delayed fadeIn closure function 
function delayFadeIn(id){
    return (function(){
        $('#'+id+'_img').fadeIn(1000);
    });
} 

//Setup three delayed fadeIns by passing closures to setTimeout
function setupFadeIns(){
    setTimeout(delayFadeIn("id1"), 1200);
    setTimeout(delayFadeIn("id2"), 2700);
    setTimeout(delayFadeIn("id3"), 3500);
}


And this will work in both MSIE and FireFox :)