javascript - 递归AJAX帖子,导致计算机运行缓慢

标签 javascript jquery ajax recursion

我有一个递归循环,在函数内部我至少有2个ajax get/post,并且递归发生在第一个ajax get之后。我的函数结构是这样的,

function Loop() {
    $.get(url, data, function(result) {
        for loop to render the result {
            // render the result here
        }
        for loop to get another data using the result {
            $.post(url, result.data, function(postResult) {
                // I don't know what it did here since 
                // I don't have an access to this post
            });
            // is there a way here that i will not proceed if the post is not done yet?
        }
        setTimeout("", 1000); // I wait for 1 second for the post to finish
        Loop(); // call the recursion
    }, "json");
}

谁能告诉我这段代码有什么问题吗?为什么我会收到计算机发出的警告,提示我的脚本导致计算机运行缓慢。我知道此代码是导致此问题的原因,但我不知道解决方法。

我知道 get 内的第二个循环会占用大量内存。有没有办法在ajax post未完成的情况下不循环返回?

最佳答案

您的setTimeout不会整齐地将代码暂停一秒钟:它只会设置一个计时器(在您的情况下为空)事件在一定时间后关闭。脚本的其余部分将继续与此并行执行。

因此,您当前调用递归函数的频率比您想象的要高得多。这是你的第一个问题。

但是,您最大的问题是,无论您在帖子的结果中做什么,这都完全属于另一个范围,并且您无法从那里突破 Loop 函数。您的代码中没有任何内容可以破坏递归,因此它是无限的,并且速度非常快,并且在此基础上发送 Ajax 请求。

您需要更详细地描述您想要实现的目标,也许有人可以告诉您应该如何实现。唯一确定的是你需要使用回调。我写了一个例子,但它做了很多假设。这与我认为您可能想要实现的目标有很多近似,但毫无疑问,您需要对此进行一些调整以满足您的需求。希望它能让您了解需要使用的工作流程:

function Loop() {
    $.get(url, data, function(result) {
        for loop to render the result {
            // render the result here
        }

        // this is what you're looping over in your second loop
        var postQueue = result.someArray;

        renderChildData(postQueue, 0);
    }, "json");
}

function renderChildData(array, index) {

   // this is just one item in the loop
   var currentItem = array[index];

   $.post(url, currentItem, function(postResult) {

       // we have received the result for one item
       // render it, and proceed to fetch the next item in the list

       index++;
       if(index < array.length) {
          renderChildData(array, index);
       }

   });
}

关于javascript - 递归AJAX帖子,导致计算机运行缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3252968/

相关文章:

javascript - 在处理旧请求时阻止新的 ajax 请求

jquery - 使用变量指定部分要渲染的 rails 名称

javascript - 停止表单在没有 JavaScript 的情况下提交

javascript - 根据键过滤对象数组的子集

javascript - 以编程方式触发 &lt;input type ="file"> 文件选择

javascript - 页面加载完成后如何运行查询?

jquery - 如何将 $(this) 作为参数传递给 jQuery 中的另一个函数?

javascript - 未捕获的类型错误 : Cannot read property 'width' of undefined

javascript - SetInterval 不刷新 Chrome 中的 HTML

javascript - 获取 li 中每个单词的第一个字母