Javascript:如何在 JavaScript 代码的执行之间添加简单的延迟?

发布于 2024-10-16 05:51:38 字数 503 浏览 4 评论 0原文

我有一个 for 循环,它在 JavaScript 代码中迭代超过 10,000 次。 for 循环创建并添加 <分区>标签放入当前页面 DOM 中的一个框中。

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

我想在每 50 < 后延迟一次分区>标签,那么该位置的代码是什么,

/* some delay function */

因为加载所有 10,000 个 << 需要花费太多时间。分区>标签。我想以 50 < 块为单位更新盒子分区>标签。

提前致谢。

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;

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

/* some delay function */

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.

thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

離殇 2024-10-23 05:51:38

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

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 的参数)。这不太可能成为问题,但如果您愿意,可以查看他的替代方案,它仅创建闭包函数一次。

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

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

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.

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.

王权女流氓 2024-10-23 05:51:38

您可以使用 window.setTimeout 函数来延迟某些代码的执行:

if(i % 50 == 0) {
    window.setTimeout(function() {
        // this will execute 1 second later
    }, 1000);
}

但是你的 JavaScript 将继续执行。它不会停止。

You could use the window.setTimeout function to delay the execution of some code:

if(i % 50 == 0) {
    window.setTimeout(function() {
        // this will execute 1 second later
    }, 1000);
}

But your javascript will continue to execute. It won't stop.

凉栀 2024-10-23 05:51:38

我会将创建 div 的代码分解为一个函数,然后通过 setTimeout 定期安排该函数的执行,如下所示:

function createThousands(data) {
    var index;

    index = 0;
    doAChunk();

    function doAChunk() {
        var counter;

        for (counter = 50; counter > 0; --counter) {
            // Are we done?
            if (index >= data.length) {
                // Yup
                return;
            }

            // ...create a div...

            // Move to the next
            ++index;
        }

        // Schedule the next pass
        setTimeout(doAChunk, 0); // 0 = defer to the browser but come back ASAP
    }
}

这使用单个闭包,< code>doAChunk 来完成这项工作。一旦其工作完成,该闭包就有资格进行垃圾收集。 (更多:闭包并不复杂< /a>)

实例

I'd break out the code creating the divs into a function, and then schedule execution of that function periodically via setTimeout, like this:

function createThousands(data) {
    var index;

    index = 0;
    doAChunk();

    function doAChunk() {
        var counter;

        for (counter = 50; counter > 0; --counter) {
            // Are we done?
            if (index >= data.length) {
                // Yup
                return;
            }

            // ...create a div...

            // Move to the next
            ++index;
        }

        // Schedule the next pass
        setTimeout(doAChunk, 0); // 0 = defer to the browser but come back ASAP
    }
}

This uses a single closure, doAChunk to do the work. That closure is eligible for garbage collection once its work is done. (More: Closures are not complicated)

Live example

葬﹪忆之殇 2024-10-23 05:51:38

因为回流需要很多时间。您应该创建一个文档片段,然后添加小孩子。

DOM 环境中什么时候会发生重排?

Javascript 性能 - Dom Reflow - Google 文章

睡觉不能解决你的问题

另一方面,您创建一个包含innerhtml 的字符串并添加到innerhtml。字符串内容确实不需要很大的性能,但是当您执行 .innerhtml 命令时,它会启动一个进程,该进程会解析您的字符串并创建元素并附加它们。你不能打断或增加延迟。

innerhtml进程不能休眠或中断。

你需要一一生成元素,并在添加50个元素后,创建一个settimeout延迟。

var frag = document.createDocumentFragment();

function addelements() {

   var e;
   for(i=0;i<50;++i) {
       e = document.createElement('div');
       frag.appendChild(e);
   }
   dest.appendChild(frag);
   window.setTimeout(addelements,1000);

}

it takes much time because the reflows. you should create a document fragment and then adding the brats.

When does reflow happen in a DOM environment?

Javascript Performance - Dom Reflow - Google Article

sleeping will not solve your problem

on the other hand, you creating a string containing the innerhtml and the add to innerhtml. the string stuff really dont needs a big performance, but when you execute the .innerhtml command, it starts a process, which parse your string and creating elements and appending them. you cant interrupt or add a delay.

the innerhtml process cannot be sleeped or interrupted.

you need to generate the elements one by one, and after 50 elemnts added, create a settimeout delay.

var frag = document.createDocumentFragment();

function addelements() {

   var e;
   for(i=0;i<50;++i) {
       e = document.createElement('div');
       frag.appendChild(e);
   }
   dest.appendChild(frag);
   window.setTimeout(addelements,1000);

}
五里雾 2024-10-23 05:51:38

这是在 javascript 中添加延迟而不挂起浏览器的真正技巧。
您需要使用带有同步方法的ajax函数,该函数将调用php页面,并且在该php页面中您可以使用sleep() php函数!
http://www.hklabs.org/articles/put-delay-in-javascript

Here is the real trick to put a delay in javascript without hanging the browser.
You need to use a ajax function with synchronous method which will call a php page and in that php page you can use the sleep() php function !
http://www.hklabs.org/articles/put-delay-in-javascript

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文