Javascript for loop blocking rest of code

530 Views Asked by At

I am having a little trouble with some Javascript that I have written. The purpose of the code is the following:

  1. Read list of SKUs from a provided .TXT file
  2. Split the data at each line
  3. For each object make a lookup on a provided JSON api to get information about the SKU
  4. Output this information into a HTML table.

Currently I have this working as I would have expected however, it seems that it not blocks any other Javascript that I try to run after the for loop.

Here is an example of my code

<script type="text/javascript">

//Set API Address


var api = "/api/AthenaService.svc/GetProductBySku/";


//Get Array of SKUs from TXT file

$.get('/Views/Locale/promoPages/LandingPages/TradeList/TradeList.txt',function(data){

//Split File into lines
var line = data.split('\n');


for(i=0;i<line.length;i++)
{

$.getJSON(api + line[i] , function(data1) {
    // Request complete, NOW we can use the data we got!
    $('.tListBody').append('<tr><td>' + data1.Title + '</td><td align="center">' + data1.Platform.Button + '</td></tr>'); 
    });


};
});



$(document).ready(function() {
$('#searchLoading').fadeOut('slow');
$('#showForm').fadeIn('slow');

$('input#tradeSearch').blur(function() {
$('input#tradeSearch').quicksearch('table#Searchable tbody tr');
});

});
</script> 

The problem I have is that none of the stuff in within document ready seems to work at all.

I have updated the code above to reflect the suggested fixed from below. It seems that code is running fine however my quicksearch jQuery plugin does not seem to be firing. I am wondering if this is related to the fact that the TR elements that it should be searching are newly created DOM elements?

Any help would be greatly appreciated.

Update:

The problem has been solved! A little reading through the documentation of the Quicksearch.js plugin and I figured out that it is possible to add entries into the quick search cache manually as part of my loop. This has fixed the problem.

Updated code below;

$(document).ready(function () {

    var api = "/api/AthenaService.svc/GetProductBySku/";

    //Get Array of SKUs from TXT file

    $.get('/Views/Locale/promoPages/LandingPages/TradeList/TradeList.txt', function (data) {

        //Split File into lines
        var line = data.split('\n');

        var qs = $('input#tradeSearch').quicksearch('.TheList tbody tr');

        for (i = 0; i < line.length; i++) {

            $.getJSON(api + line[i], function (data1) {
                // Request complete, NOW we can use the data we got!
                $('.tListBody').append('<tr><td>' + data1.Title + '</td><td align="center">' + data1.Platform.Button + '</td></tr>');
                qs.cache();

            });


        };

    });

});

Thanks for the help and suggestions all

2

There are 2 best solutions below

1
On

I know whats the problem. you are making the ajax calls inside for loop and you are expecting for loop to wait till ajax is completed. right??

for(i=0;i<line.length;i++)
{

$.getJSON(api + line[i] , function(data1) {
    // Request complete, NOW we can use the data we got!
    $('.tListBody').append('<tr><td>' + data1.Title + '</td><td align="center">' + data1.Platform.Button + '</td></tr>'); 
    });


};

ajax call is asynchronous. so $.getJSON( will make call to server and will not wait in the for loop till it complete. as soon as it makes the ajax call, it will loop through the for loop. This will give you effect as if for loop not blocking the code next to it. ... but actually for loop is completing faster withh just rasing ajax requests and then next code get executed.

1
On

Check for errors in the console, as if something is going wrong it will suspend the script, preventing the later code from running.

Also, it looks like you are making a lot of HTTP requests there (one per line in the file) which is likely to be slow.

Appending stuff to the DOM before it is ready will also cause you problems. I would move all the code inside the $(document).ready(function() { });