简体   繁体   中英

Why is this causing an infinite loop?

I'm relatively new to JavaScript and I'm trying to make a simple script. Basically, I want it to find the lowest price of an item on a website called ROBLOX. For some reason, this script is causing an infinite loop which crashes my Chrome. Can anyone help

function getLowest(id) {
    var give;
    for (var page = 1; page < 33; page++) {
        var link = "http://www.roblox.com/catalog/browse.aspx?CatalogContext=1&Subcategory=9&CurrencyType=0&pxMin=0&pxMax=0&SortType=0&SortAggregation=3&SortCurrency=0&PageNumber=" + page + "&IncludeNotForSale=false&LegendExpanded=true&Category=3";
        $.get(link, function(data) {
            for (var item in data) {
                if (data[item]["AssetId"] == id) {
                    give = data[item]["BestPrice"];
                }
            }
        })
    }
    if (give) {
        return give;
    }
}

console.log(getLowest(prompt("Enter the ID to find the lowest price of")));

I actually figured it out, thanks for the help.

This is what I ended up with:

function getLowest(id) {
    for (var page = 1; page < 33; page++) {
        var link = "http://www.roblox.com/catalog/json?browse.aspx?CatalogContext=1&Subcategory=9&CurrencyType=0&pxMin=0&pxMax=0&SortType=0&SortAggregation=3&SortCurrency=0&PageNumber=" + page + "&IncludeNotForSale=false&LegendExpanded=true&Category=3";
        $.get(link, function(data) {
            for (var item in data) {
                if (data[item]["AssetId"] == id) {
                    console.log(data[item]["BestPrice"]);
                    return;
                }
            }
        })
    }
}

getLowest(prompt("Enter the ID to find the lowest price of"));

You are not facing an infinity loop problem, but an asynchronous loading problem.

for (var page = 1; page < 33; page++) {
    $.get(link, function(data) {
        for (var item in data) {
            if (data[item]["AssetId"] == id) {
                give = data[item]["BestPrice"];
            }
        }
    })
}

Assuming you are using jQuery's $.get for querying these pages, the default behaviour for $.get is to query the page in asynchronous. Thus this loop will finish without waiting for all the callback in $.get being called, which suggests that give will remain undefined when exiting the loop.

The solution would be the one you suggest in your answer, or

  • force $.get to be synchronised by using $.ajax({ url: link, async: false }).done(function(data) {}) '
  • using async.js to do the async collection, and rewrite the function with a callback after all query work done.

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