Javascript:如何在执行javascript代码之间放一个简单的延迟? [英] Javascript: How to put a simple delay in between execution of javascript code?

查看:141
本文介绍了Javascript:如何在执行javascript代码之间放一个简单的延迟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个for循环,它在javascript代码中迭代超过10,000次。 for循环创建并添加< div>标记到当前页面DOM中的框中。

I have a for loop which iterates more than 10,000 times in a javascript code. The for loop creates and adds < div > tags into a box in the current page DOM.

for(i = 0; i < data.length; i++)
{
    tmpContainer += '<div> '+data[i]+' </div>';
    if(i % 50 == 0) { /* some delay function */ }
}
containerObj.innerHTML = tmpContainer;

我希望在每50次<< div>标签那么代码是什么

i want to put a delay after every 50 < div > tags so what will be the code at the place of

/* some delay function */

因为它花费了太多时间来加载所有10,000< div>标签。我想以50<块的形式更新盒子。 div> tags。

because its taking too much time to load all 10,000 < div > tags. i want to update the box in chunks of 50 < div > tags.

提前感谢。

推荐答案

有一个在这些情况下的方便技巧:使用0毫秒的setTimeout。这将导致您的JavaScript屈服于浏览器(因此它可以执行渲染,响应用户输入等),但不会强迫它等待一段时间:

There's a handy trick in these situations: use a setTimeout with 0 milliseconds. This will cause your JavaScript to yield to the browser (so it can perform its rendering, respond to user input and so on), but without forcing it to wait a certain amount of time:

for (i=0;i<data.length;i++) {
    tmpContainer += '<div> '+data[i]+' </div>';
    if (i % 50 == 0 || i == data.length - 1) {
        (function (html) { // Create closure to preserve value of tmpContainer
            setTimeout(function () {
                // Add to document using html, rather than tmpContainer

            }, 0); // 0 milliseconds
        })(tmpContainer);

        tmpContainer = ""; // "flush" the buffer
    }
}

注意:TJ Crowder正确地提到下面的代码将在循环的每次迭代中创建不必要的函数(一个用于设置闭包,另一个用作 setTimeout 的参数)。这不太可能是一个问题,但如果您愿意,可以查看他的替代方案,它只创建关闭功能一次。

Note: T.J. Crowder correctly mentions below that the above code will create unnecessary functions in each iteration of the loop (one to set up the closure, and another as an argument to setTimeout). This is unlikely to be an issue, but if you wish, you can check out his alternative which only creates the closure function once.

警告:尽管上面的代码将提供更愉悦的渲染体验,但不建议在页面上使用10000个标签。在此之后,每个其他DOM操作都会变慢,因为要遍历更多元素,并且对布局的任何更改都要进行更昂贵的回流计算。

A word of warning: even though the above code will provide a more pleasant rendering experience, having 10000 tags on a page is not advisable. Every other DOM manipulation will be slower after this because there are many more elements to traverse through, and a much more expensive reflow calculation for any changes to layout.

这篇关于Javascript:如何在执行javascript代码之间放一个简单的延迟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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