RobLife
RobLife

Reputation: 95

Opening new pages with

I've tried what seems like dozens of different solutions to this all with different failures. Basically I've built an array that has a bunch of IDs in it and I and using javascript to loop through them and open pages that go through an archiving process. These need to be delayed because it takes about a minute for each one to occur. Here's what I have currently:

    var i = 0
    function openPage() {
        while (i < Array.length) {
            window.setTimeout(go(i), 60000*i;);
            i++;

        }
    }


    function go(i) {
        window.open('http://localhost:12575/DD7RO2.aspx?id=' + Array[i][0]);
    }

Then I call openPage from a button press.

For some reason this throws an error of "Invalid argument" at the window.setTimeout line. I can't seem to figure out why that is. Every other iteration of this that I've tried has either opened a single window (the first in the array) and stopped, or opened everything completely disregarding the timeout. I feel like this one might actually work since it's actually doing something different. Any help would be be greatly appreciated.

Upvotes: 0

Views: 86

Answers (2)

Joe
Joe

Reputation: 47609

You are evaluating go(i) when it's passed as an argument. That function executes in the loop. Instead, you should return a function object, and that will be executed when the timer fires.

Do not do function(){go(i);}, that's a classic closure error. You would end up calling the functiongo(i) each time the event fired, but with the same, final, value of i. The scope of i is the enclosing function, so by the time the timeouts run it will have a value of Array.length - 1.

Instead something like

window.setTimeout((function (j){return function(j){go(j)}})(i), 60000*i;);

To spell that out;

(
  function (j) {
    var k = j;
    return function() {
      go(k)
     }
   }
 )(i);

This looks confusing, but that's the way JS works.

  1. It immediately executes a function with the value of i.
  2. That returns a function object, but that function is in a closure in which the value of i bound at that point in time.
  3. The function object is executed when the timeout event fires, with the value of i bound correctly.

Upvotes: 3

benhowdle89
benhowdle89

Reputation: 37454

window.setTimeout(function(){ go(i); }, 60000*i;);

Here you go!

Upvotes: 0

Related Questions