Search code examples
jqueryajaxjsonfor-loopflickr

javascript for each loop wait until process completes ajax


for (var i = 0; i < theTagNames.length; i++) {
    var url = baseURL + "?" +
        "jsoncallback=?" +
        "&method=flickr.photosets.getPhotos" +
        "&format=json" +
        "&api_key=" + api +
        "&photoset_id=" + theTagNames[i].id;
    tagID = theTagNames[i].id;
    console.log('for: ' + i)

    $.getJSON(url, {}, function (data) {
        tmpSetName = theTagNames[tmpi].title._content;
        category = theTagNames[tmpi].description._content;
        tmpi += 1;
        keepTrack = 0;

        $.each(data.photoset.photo, function (z, item) {
            if (i == limit) return false;
            console.log('each: ' + z)

            var thumbURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_s.jpg';
            var largeURL = thumbURL.replace('_s.jpg', '_b.jpg');

            keepTrack = z

            if (keepTrack == 0) {
                $('#flickrImages').append('<div style="float: left;background-color: #102C53; color: #fff; width: 690px; text-align:left; font-weight: bold; padding: 3px;" id="title' + tmpSetName + '">' + tmpSetName +
                    '<span id="span' + tmpSetName.replace(/ /g, '_') + '" style="cursor: pointer; float: right;" onclick="clickedTitle(this);">' +
                    ' [Start Slideshow]' +
                    '</span>' +
                    '</div>');
            }

            if (keepTrack <= (displayLimit - 1)) {
                $('#flickrImages').append('<span align="left" style="float: left;" id="imgDiv">' +
                    '<a style="outline: none;" rel="' + tmpSetName.replace(/ /g, '_') + '" title="" href="' + largeURL + '" id="imgLink' + tmpSetName.replace(/ /g, '_') + i + '">' +
                    '<img id="img' + i + '" src="' + thumbURL + '" style="border: 1px solid #102C53; margin: 3px;" alt="' + tmpSetName + '" />' +
                    '</a>' +
                    '</span>');
            } else if (keepTrack == (displayLimit + 1)) {
                showMoreImages = true;
            } else {
                $('#flickrImages').append('<span align="left" style="float: left; display: none; visibility: hidden;" id="hidden' + tmpSetName.replace(/ /g, '_') + '">' +
                    '<a style="outline: none;" rel="' + tmpSetName.replace(/ /g, '_') + '" title="" href="' + largeURL + '" id="imgLink' + tmpSetName.replace(/ /g, '_') + i + '">' +
                    '<img id="img' + i + '" src="' + thumbURL + '" style="border: 1px solid #102C53; margin: 3px;" alt="' + tmpSetName + '" />' +
                    '</a>' +
                    '</span>');
            }
        });
    });
}
}

Currenlty the above code works but when i refresh the page it tends to get the images out of order (wrong heading with the images & also wrong images that go with that heading). It seems to be getting ahead of itself since the $.each could have over 50+ images to get per theTagName.

Sometimes its in the correct order but often times it is not.

Is it possible to pause the for (var i = 0; i < theTagNames.length; i++) { until all images in the $.each have been found and appened to the flickrImages div?


Solution

  • You should put the whole $.getJSON(url, {}, function (data) { ... in a separate function outside the for loop and then pass in i otherwise the value of i will change as you have an async situation.

    Also, you should use a different variable name for the index parameter of your $.each function.

    So your code would look something like this:

    for (var i = 0; i < theTagNames.length; i++) {
        // stuff
        getFlkrJSON(data, i);
    }
    
    function getFlkrJSON(data, i){
        $.getJSON(url, {}, function (data) {
            //stuff
        }
    }