1

This is what i have. My problem is, each loop doesn't wait setTimeout to complete its job. I have 2 console.log('elmDuration = ')... before slider.goToNextSlide executed. Which is wrong. I would use generator functions and yield if this is a server side code, but not.

$('li').each(function(index, elm){
        var image = $(elm).find('img')[0];
        var video = $(elm).find('video')[0];
        var media = image || video;

        var elmDuration = $(media).attr('data-duration');
        console.log("elmDuration = ", elmDuration);
        (function(){
            setTimeout(slider.goToNextSlide, elmDuration * 1000);
        })();
});

I am stuck with this. Thanks.

0

3 Answers 3

3

If you want to advance to the next element when the timeout finished, you have to do that manually:

var $lis = $('li');
var index = 0;

function next(index) {
    var elem = $lis[index];
    var image = $(elm).find('img')[0];
    var video = $(elm).find('video')[0];
    var media = image || video;

    // if there is always going to be either an img **or** a video element, 
    // you can directly do
    // var  elmDuration = $(elem).find('img, video').attr('data-duration');
    var elmDuration = $(media).attr('data-duration');
    console.log("elmDuration = ", elmDuration);

    setTimeout(function() {
        slider.goToNextSlide();
        if (index < ($lis.length - 1)) {
            next(++index);
        }
   }, elmDuration * 1000);
}

next(index);
Sign up to request clarification or add additional context in comments.

Comments

3

each loop is not going to wait for setTimeout. It will execute for all elements in $('li') before setTimeouts start firing. The purpose of setTimeout is to let the code that calls it proceed without interruption and execute the first parameter when timeout occurs.

Comments

2

You have to take the code out of the setTimeout if you want it to execute inside the loop. SetTimeout is a way to execute code in x milliseconds, but it won't execute until the single javascript thread is available. The loop will keep the thread busy, so all the seTimeouts will have to wait until the end.

2 Comments

understood. But i need to wait for element-specific seconds before execute the code inside setTimeout. How can i handle this?
you already are doing it. there is no need to wrap setTimeout call in another function.

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.