kibowki
kibowki

Reputation: 4376

How to delay a for loop execution in Javascript

As the title states, I need to delay each iteration of a for loop. Here is what I have found of several of Stack Overflow posts:

var my_event_num = $(this).data('eventnum');

for (var i = 0; i < motion_media[my_event_num].length; i++) {
    (function(index) {
        setTimeout(function() { 
            $("#slideshow-" + my_event_num).attr('src', 'motion-media/' + motion_media[my_event_num][index]) 
        }, 2000);
    })(i);
}

motion_media - an array of arrays. my_event_num - a valid pointer to an index in motion_media.

However, this (and several other solutions) didn't work for me - it immediately executes the entire for loop with no timeout. Would recursion be the way to go? How could I implement such a solution?

Upvotes: 0

Views: 521

Answers (2)

Bergi
Bergi

Reputation: 664620

Would recursion be the way to go?

Yes, using pseudo-recursion is an easy and probably the best solution.

var my_event_num = $(this).data('eventnum');
(function go(index) {
    if (i < motion_media[my_event_num].length) {
        $("#slideshow-" + my_event_num).attr('src', 'motion-media/' + motion_media[my_event_num][index]);
        setTimeout(function() {
            go(i+1);
        }, 2000);
    }
}(0));

However, you did ask about promises as well. Using the delay and promise animation queue methods of jQuery, you can devise a similarly easy promise sequence:

var my_event_num = $(this).data('eventnum');
var promise = $.when();
for (var i = 0; i < motion_media[my_event_num].length; i++) {
    promise = promise.then(function() {
        return $("#slideshow-" + my_event_num)
          .attr('src', 'motion-media/' + motion_media[my_event_num][index])
          .delay(2000)
          .promise();
    });
}

Upvotes: 0

Asit
Asit

Reputation: 468

Try this code :

var my_event_num = $(this).data('eventnum');

for (var i = 0; i < motion_media[my_event_num].length; i++) {
    (function(index) {
        setTimeout(function() { 
            $("#slideshow-" + my_event_num).attr('src', 'motion-media/' + motion_media[my_event_num][index]) 
        }, 2000*i);
    })(i);
}

Upvotes: 1

Related Questions