防止AJAX队列阻止浏览器 [英] Prevent AJAX Queue from blocking browser

查看:115
本文介绍了防止AJAX队列阻止浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:简化示例.

我有一个包含1000个表行的页面.对于每一行,我需要通过AJAX调用在服务器上做一些工作",然后在回调中,更新表行并说完成".

I've got a page with 1000 table rows. For each row, i need to "do some work" on the server via an AJAX call, then in the callback, update that table row saying done.

最初,我尝试在.each选择器中触发1000个ajax请求,但是浏览器被锁定.

Initially i tried just firing off the 1000 ajax requests inside the .each selector, but the browser was locking up.

因此,我将其更改为尝试使用内部ajax计数器,因此一次只能触发50个.

So i changed it to try and use an internal ajax counter, so only ever fire off 50 at a time.

代码如下:

$('#do').click(function () {
    var maxAjaxRequests = 50;
    var ajaxRequests = 0;
    var doneCounter = 0;
    var toDo = $('#mytable tr').length;

    $.each($('#mytable > tr'), function (i, v) {
        while (doneCounter < toDo) {
            if (ajaxRequests <= maxAjaxRequests) {
                ajaxRequests++;
                doAsyncStuff($(this), function () {
                    ajaxRequests--;
                    doneCounter++;
                });
            } else {
                setTimeout(function() {
                }, 1000);
            }
        }
    });
});

function doAsyncStuff(tr, completeCallback) {   
    $.ajax({
        url: '/somewhere',
        type: 'POST',
        dataType: 'json',
        data: null,
        contentType: 'application/json; charset=utf-8',
        complete: function () {
            completeCallback();
        },
        success: function (json) {
            // update ui.
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            // update ui.
        }
    });
}

但是浏览器仍处于锁定状态.即使我可以看到请求成功返回(通过Fiddler),也永远不会进入$.ajax完整回调.因此,它只是处于睡眠,循环,睡眠等状态,因为从未返回过回调.

But the browser is still being locked up. It never goes into the $.ajax complete callback, even though i can see the request coming back successfully (via Fiddler). Therefore its just sleeping, looping, sleeping, etc because the callback is never returned.

我觉得整个doAsyncStuff函数需要异步进行吗?

I've got a feeling that the entire doAsyncStuff function needs to be asynchronous?

关于我做错了什么(或者我如何做得更好)的任何想法?

Any ideas on what i am doing wrong (or how i can do this better)?

推荐答案

您正在.each回调函数内执行while循环,因此ajax请求多于1000,最糟糕的是1000 * 1000.

You are doing a while loop inside the .each callback function, so there is much more ajax request than 1000, the worst is 1000*1000.

您可以将每个ajax请求延迟不同的时间.

You could delay each ajax request with different time.

$('#do').click(function () {
    $('#mytable > tr').each(function (i, v) {
        var $this = $(this);
        setTimeout(function () {
            doAsyncStuff($this, function () {
               console.log('complete!');
            });
        }, i * 10);
    });
});

这篇关于防止AJAX队列阻止浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆