简体   繁体   中英

Opening different pages timed in a For-Loop

it is me again with a strange question :) I would like to write a for loop which opens new windows with different lat and lng values. These are geocordinates. I have tried the code below. But it does not work and always opens openWin(100,20) I have no idea how I could possibly find a work around. Therefore every suggestion and proposal is welcome. Ideally I would also like to check all lng values from -180 to 180 as well in a second loop. But due to the fact the code below does not work I did not try to implement a second one.

function init() {
    var i = 2000;

    for(var lat=-90;lat<=90;lat+=10) {
        var lng = 20; // -180 --> 180
        setTimeout(function(){openWin(lat,lng);}, i);
        i+=2000;
        setTimeout(function(){closeWin();}, i);

    }
}

Because your setTimeout() runs sometime later, the value of lat will be that at the end of your for loop, not what you want it to be.

You can fix it with an IIFE closure that captures the value of the variable and holds it for use later in the setTimeout() :

function init() {
    var i = 2000;

    for(var lat=-90;lat<=90;lat+=10) {
        var lng = 20; // -180 --> 180
        (function(lat, lng) {
            setTimeout(function(){openWin(lat,lng);}, i);
            i+=2000;
            setTimeout(function(){closeWin();}, i);
        })(lat, lng);
    }
}

FYI, it isn't clear exactly what you're trying to do with the i value. I can't tell if you want that inside or outside the closure or when exactly you want it incremented. It is also not clear how closeWin() knows which window to operate on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM