0

I've been working on this for days and I can't seem to find a solution.

I want this script to wait until the user presses the enter key after the first value has been inputted into the field. I want the script to keep doing this every time a value is added, but I can't quite seem to find out how to do this.

$(document).ready(function() {

  console.log("script loaded");

  var apiKey = "";
  var itemImage = $(".title-wrap img");
  var itemList = [];
  var i = 0;
  var addPage = false;

  // Run through all images and grab all item ID's.
  function scrapeItems() {
    itemImage.each(function() {
      var grabItemID = $(this).attr("src").match(/\d+/)[0];
      var disabled = $(this).closest("li.clearfix").hasClass("disabled");

      // Add item number as class for easy reference later.
      $(this).addClass("item-" + grabItemID);

      // If the item's row has "disabled" class, skip this item.
      if (disabled) {
        return true;
        scrapeItems();
      }

      // Add item to array.
      itemList.push(grabItemID);
    });
  }

  scrapeItems();

  // Call the API request function and start gathering all bazaar prices.
  function getPricing() {
    console.log("script started");

    $.each(itemList, function(key, value) {

      // Set three second timer per API request.
      setTimeout(function() {

        // Actual API request.
          return $.ajax({
            dataType: "json",
            url: "https://api.torn.com/market/" + value,
            data: {
              selections: "bazaar",
              key: apiKey
            },

            // When data is received, run this.
            success: function(data) {

              console.log(value + " request was successful");

                var cheapest = null;

                // Run through all results and return the cheapest.
                $.each(data["bazaar"], function(key, val) {
                  var cost = val["cost"];

                  if (cheapest == null || cost < cheapest) {
                    cheapest = cost;
                  }
                });

                var inputMoney = $(".item-" + value).closest("li.clearfix").find(".input-money:text");

                inputMoney.val(cheapest - 1).focus();
        
        
        
        
                // I WANT THE FUNCTION TO WAIT HERE UNTIL THE USER PRESSES ENTER
        
        
        

              },

            // When data is not received, run this.
            error: function() {
              console.log(value + " request was NOT successful");
            }
          });

      }, key * 3000);

    });
  }

  function checkPage() {
    var i = 0;
    var url = window.location.href;

    i++

    setTimeout(function() {
      if (url.indexOf("bazaar.php#/p=add") > 0) {
        addPage = true;
        addButton();
      } else {
        checkPage();
      }
    }, i * 1000);

  }

  checkPage();

  function addButton() {
    $("#inventory-container").prepend('<button id="start-button" style="margin-bottom:10px;margin-right:10px;">Run Auto-pricing script</button><p id="s-desc" style="display:inline-block;font-weight:bold;text-transform:uppercase;">Press the enter key after the price has shown up!</p>');
  }

  $(document).on("click", "#start-button", function() {
    getPricing();
  });

});

I'm at a complete loss on this one guys, so all help is appreciated!

  • `scrapeItems();` after `return` is not reachable. – Sebastian Simon Jul 15 '18 at 18:15
  • Possible duplicate of [pause function until enter key is pressed javascript](https://stackoverflow.com/questions/17176046/pause-function-until-enter-key-is-pressed-javascript) – t.niese Jul 15 '18 at 18:26
  • 8You can only pause `async` functions, and if this is an options depends on the browser you want to target, or if you want to use a transpiler like babel (it will create a large amount of additional code to emulate async functions). For regular functions you need to do it as described in the duplicate. – t.niese Jul 15 '18 at 18:28

1 Answers1

0

I think you should break down your code a bit more, and move the "on enter" part of the code into a separate function instead of waiting for user input within that success callback.

e.g in pseudo code, different stages of the scraping

let priceData;
const preProcessPriceData = (data) => {
    // do some pre-processing, validate, change data formats etc
    // return processed data
};
const processPriceData = (data) => {
    // called when price data is ready and user pressed enter
    // in other words - script continues here
    console.log(priceData, 'or', data);

};

scrapeItems();

// in get prices function - remove event handler
$("#some-input-user-is-pressing-enter-in").offOnEnter(processPriceData);
priceData = null;
getPrices().then((data) => {
    priceData = data;
    let processedData = preProcessPriceData(data);
    // add listener to wait for user input
    $("#some-input-user-is-pressing-enter-in").onEnter(() => {
        // script continues after user presses enter
        processPriceData(processedData);
    });
});
Rainer Plumer
  • 3,693
  • 2
  • 24
  • 42