Thursday 31 March 2016

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...