Javascript 延迟函数,但让循环等待它

Javascript Delay function but let loop wait for it

本文关键字:循环 等待 延迟 函数 Javascript      更新时间:2023-09-26

我知道这不是一个好主意,但每个程序员都想学习更多。目前,我一直在尝试网络抓取。第一次创建脚本并运行它会阻止我的 IP 地址。我错了,因为在我的脚本中我向网站发送了太多请求,这样就会给网站带来很多流量,让他们认为我是入侵者,我想到了这个想法来延迟我的请求,如何让我的循环等待函数完成?我不想使用这样的东西。这将每 5 秒执行一次

(function(links){ 
    setTimeout(function() { scrapeAnotherLink(links); }, delay); 
})(result[val]); 
 delay += 5000;

我想等待我的 ajax 请求从提供的链接完成报废,然后等待 5 秒,然后再次执行。

我的代码。

抓取链接。

$('#scrape').click(function() {
          $.ajax({
          type: 'get',
          url: 'scrape.php',  
          data:{Param:1},
          dataType: 'json',
          cache: false,
              success: function(result) {  
                for(var val in result) { 
                  link = result[val];
                      scrapeAnotherLink(link);
                }
              },
          });
    });

function scrapeAnotherLink(link){
   //Some ajax here
    setTimeout(function() { 
      output_log(link);
   }, 5000);  
}
function output_log(str){
    $('#output').append(str+'<br/>');
}

我读到一些刮板池IP地址,但我不知道如何

这样的事情就可以完成了这项工作。不要使用循环,而是进行递归调用,该调用将在上一个 ajax 请求结束时执行。下面的代码有一些假设,但它传达了这个想法。

function executeAjax() { 
    $.ajax({
        type: 'get',
        url: 'scrape.php',  
        data:{Param:1},
        dataType: 'json',
        cache: false,
        success: function(links) {  
            scrapeAnotherLink(links, 0);
        }
    });
}
function scrapeAnotherLink(links, index){
   //Some ajax here
    function executeCall(){
        $.ajax({
            url : links[index],
            success : function(str) {
               output_log(str);
               scrapeAnotherLink(links, ++index);
            }
        });
    }
    setTimeout(executeCall, 5000); 
}
function output_log(str){
    $('#output').append(str+'<br/>');
}