John C
John C

Reputation: 35

jquery each delay without effect

I am trying to use the each function and have a pause between the execution of each iteration. Specifically, I want the script to open a bunch of URLs in new windows, but I want there to be a 2 second pause between each window opening. Right now each of the links opens without a pause in between. Below is my code right now. I don't know how to use the delay() function since I'm not then calling another jQuery effect after the delay. I've also tried setTimeout to no avail. What am I missing?

    $('.url').each(function() {
        url = $(this).attr("href");
        window.open('http://www.google.com' + url);
    });

Upvotes: 1

Views: 2747

Answers (1)

mVChr
mVChr

Reputation: 50185

You need to use the index parameter of the .each()DOCS method in order to multiply your setTimeout delay by the index of the item. This is because the iterations in the each loop are processed immediately, so you'll essentially be setting delays of 0, 2000, 4000, 6000, etc:

$('.url').each(function(i) {
    var url = $(this).attr("href");
    setTimeout(function() {
      window.open('http://www.google.com' + url);
    }, 2000*i);
});

Upvotes: 6

Related Questions