Search code examples
jqueryvideosettimeoutclonedelay

jquery how to delay play of each cloned video


I want to made a visual effect playing the same video multiple times at once but with a little delay amound them. First video will be playing at start and the rest in a cascade way with 1000 delay for each, so the last one will be playing the number of cloned videos x1000.

But I am not able to delay playing for each clone. Just pause or play all of them at the same time. What am I missing?

    <body>
    <div class="masonry-css" id="gridVideos">
    </div>
    <script type="text/javascript">
        var cloneCount = 1;
        var count = 0;
        $.fn.multiply = function (numCopies) {
            var newElements = this.clone(true, true);
            for (var i = 1; i < numCopies; i++) {
                count++;
                newElements  = newElements.add(this.clone(true, true)
                                          .attr('id', 'Videos' + cloneCount++)
                                          .insertAfter($('[id^="gridVideos"]:last'))
                );
            }
            return newElements;
        };
        var repeVideos = $('<video/>', {
            'id': 'myVideo',
            'class': 'masonry-css-videos',
            'width': '320',
            'muted': 'true',
            'loop': 'true',
            'src': 'videos/AVIDEAlow.webm',
            'type': 'video/webm',
        });
        var repetimos = $('<div/>', {
            'id': 'Videos0',
            'class': 'masonry-css-item',
        });
        var todoDivsVideo = repetimos.append(repeVideos);
        $('#gridVideos').append(todoDivsVideo.multiply(9));
        $('video').trigger('pause');
        $('[id^="Videos"]').find('video').each(function(){
                        setTimeout(function(){$('video').trigger('play');
                         });
                        });


Solution

  • The first paramater of .each() in jQuery is the current index, so you can use index * 1000 to increment the delay during your loop

    The second paramater is the current element, so you can use this instead of the video selector as well

    $('[id^="Videos"]').find('video').each(function(index, video) {
      setTimeout(function() {
        $(video).trigger('play');
      }, index * 1000)
    });