如何阻止激烈的Javascript循环冻结浏览器 [英] How to stop intense Javascript loop from freezing the browser

查看:117
本文介绍了如何阻止激烈的Javascript循环冻结浏览器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Javascript解析一个包含大约3,500个元素的XML文件。我正在使用jQueryeach函数,但我可以使用任何形式的循环。

问题是浏览器在循环执行时冻结了几秒钟。在不降低代码速度的情况下停止冻结浏览器的最佳方法是什么?

I'm using Javascript to parse an XML file with about 3,500 elements. I'm using a jQuery "each" function, but I could use any form of loop.
The problem is that the browser freezes for a few seconds while the loop executes. What's the best way to stop freezing the browser without slowing the code down too much?

$(xmlDoc).find("Object").each(function() {
    //Processing here
});


推荐答案

我会放弃每个功能,转而支持一个for循环,因为它更快。我还会使用setTimeout添加一些等待,但只是每隔一段时间,只有在需要时。您不希望每次等待5毫秒,因为处理3500条记录大约需要17.5秒。

I would ditch the "each" function in favour of a for loop since it is faster. I would also add some waits using the "setTimeout" but only every so often and only if needed. You don't want to wait for 5ms each time because then processing 3500 records would take approx 17.5 seconds.

下面是一个使用for循环处理100条记录的示例(您可以以5毫秒的间隔进行调整,这会产生175毫秒的开销。

Below is an example using a for loop that processes 100 records (you can tweak that) at 5 ms intervals which gives a 175 ms overhead.

var xmlElements = $(xmlDoc).find('Object');
var length = xmlElements.length;
var index = 0;
var process = function() {
  for (; index < length; index++) {
    var toProcess = xmlElements[index];
    // Perform xml processing
    if (index + 1 < length && index % 100 == 0) {
        setTimeout(process, 5);
    }
  }
};
process();

我还会对xml处理的不同部分进行基准测试,看看是否存在可能存在瓶颈的问题固定。您可以使用firebug的探查器在firefox中进行基准测试,并像这样写入控制台:

I would also benchmark the different parts of the xml processing to see if there is a bottleneck somewhere that may be fixed. You can benchmark in firefox using firebug's profiler and by writing out to the console like this:

// start benchmark
var t = new Date();
// some xml processing
console.log("Time to process: " + new Date() - t + "ms");

希望这有帮助。

这篇关于如何阻止激烈的Javascript循环冻结浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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