1

I'm trying to delay the each loop by using setTimeout.

  $(".video_nav .item_container > .item").each(function() {
var button = $(this);
            setTimeout(function(i) {
                 alert("test");
                button.trigger("click");

            },2000);
        });

The alert or the click events aren't firing. Where did i go wrong? I want each loop iteration to be 2 seconds.

user892134
  • 2,906
  • 13
  • 50
  • 101
  • Is the selector correct? if yes, then at-least `alert()` should work. – Tushar Apr 12 '16 at 14:26
  • `this` is not what you think it is. – SLaks Apr 12 '16 at 14:26
  • @SLaks i changed that and i should get an alert every 2 seconds but nothing? – user892134 Apr 12 '16 at 14:30
  • I finally get an alert but what happens is after 2 seconds the alerts come one after another instead of 2 seconds inbetween. – user892134 Apr 12 '16 at 14:32
  • This is the case because setTimeout is working asynchronously - it will create a new thread each time you call it, not waiting for completion. Each thread will then fire after 2 seconds. You need to use a synchronous method which waits "in place" of the loop for completion. This does not exist out of the box in JavaScript - [here](http://stackoverflow.com/a/13205283/1016343) you can find such a "busy wait" function. – Matt Apr 12 '16 at 15:56

2 Answers2

1

I don't know if i get the question right, but you want to loop trough some elements after 2 seconds?

The solution for this problem by using Jquery:

You can use the Delay-method (https://api.jquery.com/delay/) in combination with the Queue-method (https://api.jquery.com/queue/)

$(".video_nav .item_container > .item").each(function() {
    var button = $(this);
    $(button).delay(2000).queue(function(){
      alert("test");
      button.trigger("click");
   });
});

For a working example please check this link: https://jsfiddle.net/crix/bb4nbkts/

Hope this helps for you.

Crix
  • 76
  • 3
-1

Try to make use of arrow function at this context,

$(".video_nav .item_container > .item").each(function(i) {
  setTimeout(() => { 
   $(this).trigger("click");
  }, i * 2000);
});

The problem in your code is the this context. Inside plain setTimeout's callBack the this will point to window. So there comes the arrow function, it will bind its nearest context's this value into it.

Also you have to give a delay of (i * 2000), then only the delay will become 0,2000,4000 and so on. That will make you to see the callBack works with a interval of 2 secs each.

Rajaprabhu Aravindasamy
  • 63,064
  • 13
  • 90
  • 119