Paul Ledger
Paul Ledger

Reputation: 1135

Javascript set up Timeout Functions within a for loop

I have a loop that select and object and fades that object in, but when the loop is executed the object id stays at the last entry;

    var ordered = Array(elements.length);
            var x = 0;
            $('#' + that.options.slide_name + '_' + that.nextslide).children().each(function () {
                ordered[x] = $(this);
                $(this).fadeOut(1);
                $(this).attr('id','current_slide_content_' + x);
                x++;
            });
//fade each element
            var time = that.options.fade_speed / ordered.length
            var overlap = time / that.options.fade_step;
            //time = time + overlap;
            var wait = 0;
            var num = 0;
            var i = null;
            var funcs = Array(ordered.length);
            for(var a = 0; a < ordered.length; a++){
                var w = wait;
                var id = $('#current_slide_content_' + a);
                window.setTimeout( function (event) {
                    id.fadeIn(time);
                    console.log(id);
                },w);
                //$('#current_slide_content_' + a).fadeIn(time);  <-- on its own works, error is with the wait time
                wait = time + wait; 
            }

I narrowed down the error to be in the final loop that actually adds the timeout function.

for(var a = 0; a < ordered.length; a++){
                var w = wait;
                var id = $('#current_slide_content_' + a);
                window.setTimeout( function (event) {
                    id.fadeIn(time);
                    console.log(id);
                },w);
                //$('#current_slide_content_' + a).fadeIn(time);  <-- on its own works, error is with the wait time
                wait = time + wait; 
            }

When the id of the element is logged it should be:

foo_0 foo_1 foo_2

But instead it displays as:

foo_2 foo_2 foo_2

I have been on this for days and restarted several times, how do i format the id correctly for each of my Timeout functions?

Upvotes: 1

Views: 69

Answers (1)

Hacketo
Hacketo

Reputation: 4997

should try :

window.setTimeout( (function(time_, id_){
    return function (event) {
        id_.fadeIn(time_);
        console.log(id_);
    }
})(time,id),w);

This is a closure to save the value of time and id in the scope of the function

Upvotes: 2

Related Questions