setTimeout with each loop does not work [duplicate]

0
count = 1;
$("a.btns").each(function() {
    if ($(this).parent("span").attr("id") == "btn_default") {
        return;
    }

  count++;
these = $(this);

setTimeout(function() {
$(these).click();
  }, 10000 * count);
});

The problem should be very simple to solve, but to break the head ..

Basically, I try to run about 10 buttons on the page, which meet the "btns" class, and every 10 seconds (as I defined in the timeout), click the button (one at a time, code).

But in practice, only the last button is clicked every time. It seems that in any setTimeout call, the "inves of these" is each button, it takes the last of the loop each.

What to do in this case?

Thank you

    
asked by anonymous 03.02.2018 / 22:44

1 answer

1

The problem is as I explained in my comment. The solution would be to arrange a way to keep the reference to the button element at the time of calling the function inside setTimeout . I thought of two:

You can play your setTimeout to a parameterized auxiliary function:

count = 1;
$("a.btns").each(function() {
    if ($(this).parent("span").attr("id") == "btn_default") {
        return;
    }

  count++;
  these = $(this);
  clickTimeout(these, 10000 * count);
});

function clickTimeout(el, time){
    setTimeout(function() {
        $(el).click();
    }, time);
}

Or, in a slightly uglier way, you can use the Javascript bind () to store the parameterized call directly within setTimeout :

count = 1;
$("a.btns").each(function() {
    if ($(this).parent("span").attr("id") == "btn_default") {
        return;
    }

  count++;
  these = $(this);

  setTimeout((function(el) {
      $(el).click();
  }).bind(this, these), 10000 * count);
});

I hope I have helped.

    
03.02.2018 / 23:39