1

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?

1

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

I would say fix the inner id.fadeIn to id_.fadeIn and it looks like it's ready to go ;)
I cant believe it was something a simple as that, thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.