Javascript(jQuery)在完成所有工作后仍然在运行

时间:2009-10-13 00:33:23

标签: jquery

我正在使用jQuery来批量加载一个庞大的表。我正在加载初始行,然后我进行$ .ajax调用以将行追加到表的主体。完成插入下一行行后,我调用该方法处理下一行行。见下面的代码。问题是,即使在加载了所有内容之后,javascript仍然声称正在执行 - 当我去导航到另一个页面时,抱怨有一个javascript例程减慢了页面并且我想要中止它。此时,它不应该运行!最初从$(function(){...})例程调用此例程(准备就绪)。有什么想法,我应该在它完成所有工作之后阻止它继续吗?

        function processNextChunk(c, t, s, p, x) {
        var args = "{company_ID:" + c + ",shareholdingType:" + t + ",startIndex:" + s + ",pageSize:" + p + ",stack:'" + x + "'}";
        //alert(args);
        $.ajax({
            type: "POST",
            url: "TestStructure6.aspx/GetNextHierarchyPage",
            data: args,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                //Append the content to the bottom of the table tag.
                //Returning 2 arguments from the result, hence the split (initial
                //value is an int, so not a big deal using pipe as a delimiter)
                if (msg.d.length > 0) {
                    var slash = msg.d.indexOf('|');
                    var r;
                    if (slash > 0) {
                        x = msg.d.substr(0, slash);
                        r = msg.d.substr(slash + 1, msg.d.length - slash);
                        $('#h  > tbody').append(r);
                        if (r.length > 0) {
                            var percent = (s + p) / totalRows * 100;
                            $('#counter').html(parseInt(percent) + '%');
                            setTimeout('processNextChunk(' + c + ', ' + t + ', ' + (s + p) + ', ' + p + ', "' + x + '")', 0);
                            //processNextChunk(c, t, s + p, p, x)
                        }
                        else {
                            $('#counter').html('');
                        }
                    }
                }
                return true;
            }
        });
        return true;
    }

3 个答案:

答案 0 :(得分:2)

这可能会或可能不会解决您的问题,但您不应该使用字符串参数调用setTimeout

相反,你应该给它一个函数,如:

setTimeout(function() {
    processNextChunk(c, t, s + p, p);
}, 0);

此外,您可以撰写$('#counter').html('')

,而不是撰写$('#counter').empty()

要解决您的问题,您确定setTimeout电话会永远递归吗?

答案 1 :(得分:0)

在检索完所有行的情况下,我无法确定返回的数据。我假设它应该不通过检查:

r = msg.d.substr(slash + 1, msg.d.length - slash);

如果是这种情况,您可以在以下的else子句中使用clearTimeout():

$('#counter').html('');

答案 2 :(得分:0)

您正在调用setTimeout(...,0)也称为零超时。换句话说,您不允许浏览器更新/重绘。

请注意,这取决于浏览器 - 多年来在各种机器上进行的一些测试表明winxp至少需要50的超时,而linux需要10的超时。这似乎与操作系统调度的最小时间片有关。

如果您正在快速连接(例如:localhost开发),也许ajax调用响应速度足够快,因此将其设置为零是一个问题...

你的代码看起来可以做到只需将超时增加到更大的值,比如1秒,没有不良影响。

[使用字符串参数调用setTimeout是完全有效的,但看起来你没有正确引用。 ]