Wednesday, March 21, 2018

Pass urls stored in array to window.open in for loop - Javascript

I'm trying to step through an array and pass my urls stored there to the window.open function. This is what I have.



$('a.linked').click(function(e) {
e.preventDefault();
var i;
var urls = ['http://example.com', 'http://example2.com', 'http://example3.com'];

for (i = 0; i < urls.length; i++) {
var ts = i*3500;
setTimeout(function(){window.open(urls[i]); }, ts);
}
});


This is opening the new windows at the correct timing but I'm getting about:blank. I thought it might be not escaping quotes.




The duplicate answer says I'm losing my value of i However, when I remove the setTimeout I get all the new windows with the
correct urls. The following code demonstrates not losing the value of i.




$('a.linkedinProfiles').click(function(e) {
e.preventDefault();
var i;
var urls = ['http://example.com', 'http://example2.com', 'http://example3.com'];
for (i = 0; i < urls.length; i++) {
var ts = i*3500;
{window.open(urls[i]); };
} });


I know this has to be something simple I am missing. Thanks in advance.

No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...