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

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

问题描述

我正在使用 Javascript 来解析包含大约 3,500 个元素的 XML 文件.我正在使用 jQuery每个"函数,但我可以使用任何形式的循环.
问题是浏览器在循环执行时冻结了几秒钟.在不使代码减慢太多的情况下停止冻结浏览器的最佳方法是什么?

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
});

推荐答案

我会放弃each"函数,转而使用 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 循环的例子,它以 5 毫秒的间隔处理 100 条记录(你可以调整它),这会产生 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天全站免登陆