Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

i want to stop ajax request after 10 request in async function

i have async function sends ajax request based on the last ajax response the function works fine but it sends many requests i need to make interval 5 seconds between each request and i want to stop ajax calls after 20 request.

this is the The JS code

$(document).ready(function(e){

$(document).on('input', '#repSlider2', function() {
    $('#repoutput2').html( $(this).val() );
});

async function scrapePage(url, data = {}) {
  const response = await $.ajax({
    url,
    data,
    type: "POST",
    dataType: "json",
  });
    var output2 = "";
    var FbUsersId = $('#FbUsersId').val();
  console.log(response);
             $.each(response, function(key, value) { 
               output2 += value.group_id+'\r\n';
                });  
            $("#FbUsersId").val(FbUsersId+output2);
            var text = $('#FbUsersId').val();
            text = text.replace(/(?:(?:\r\n|\r|\n)\s*){2}/gm, "");
            // $(FbUsersId).val(text);


  // If there is no next page, show the error.
  const nextPage = 'exGoupsReq.php?next='+response[0].next_page;
  if (typeof nextPage === 'undefined') {
    $(".successMSG").html(
      Swal.fire({
        icon: "danger",
        title: "No more pages",
        showConfirmButton: false,
        timer: 2000,
        timerProgressBar: true,
      }).then(function (isConfirm) {
        if (isConfirm) {
        } else {
          //if no clicked => do something else
        }
      })
    );

    return;
  }

  // Otherwise scrape the next page.
  await scrapePage(nextPage, data);
}

$("#getUsersId").on("submit", async function (e) {
  e.preventDefault();
  var keyword = $("#Keyword").val();
  var fbAcc = $("#fbAccs").val();

  const data = { 
    Keyword: keyword, 
    fb_acc: fbAcc 
  };

  $(".submitBtn").attr("disabled", "disabled");

  await scrapePage("exGoupsReq.php", data);

});



});

I tried a lot, but all failed

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You just need to set a delay function with promise and setTimeout

async function delay(ms = 300) {
  return new Promise((resolve, reject) => setTimeout(resolve, ms))
}

which should delay the execution of the next scrapePage function by 5 seconds.

await delay(5000)
await scrapePage(nextPage, data);

And set a counter and on each request increment it with one, and when it reaches 20, just return the function and stop the recursion.

This the full example of the code.

$(document).ready(function (e) {
    $(document).on("input", "#repSlider2", function () {
        $("#repoutput2").html($(this).val());
    });

    async function delay(ms = 300) {
        return new Promise((resolve, reject) => setTimeout(resolve, ms))
    }
    let count = 0;

    async function scrapePage(url, data = {}) {
        count++;
        if (count >= 20) {
            return;
        }
        const response = await $.ajax({
            url,
            data,
            type: "POST",
            dataType: "json",
        });
        var output2 = "";
        var FbUsersId = $("#FbUsersId").val();
        console.log(response);
        $.each(response, function (key, value) {
            output2 += value.group_id + "\r\n";
        });
        $("#FbUsersId").val(FbUsersId + output2);
        var text = $("#FbUsersId").val();
        text = text.replace(/(?:(?:\r\n|\r|\n)\s*){2}/gm, "");
        // $(FbUsersId).val(text);

        // If there is no next page, show the error.
        const nextPage = "exGoupsReq.php?next=" + response[0].next_page;
        if (typeof nextPage === "undefined") {
            $(".successMSG").html(
                Swal.fire({
                    icon: "danger",
                    title: "No more pages",
                    showConfirmButton: false,
                    timer: 2000,
                    timerProgressBar: true,
                }).then(function (isConfirm) {
                    if (isConfirm) {
                    } else {
                        //if no clicked => do something else
                    }
                })
            );

            return;
        }
        await delay(5000)
        // Otherwise scrape the next page.
        await scrapePage(nextPage, data);
    }

    $("#getUsersId").on("submit", async function (e) {
        e.preventDefault();
        var keyword = $("#Keyword").val();
        var fbAcc = $("#fbAccs").val();

        const data = {
            Keyword: keyword,
            fb_acc: fbAcc,
        };

        $(".submitBtn").attr("disabled", "disabled");

        await scrapePage("exGoupsReq.php", data);
    });
});

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading