用Java语言执行长任务 [英] Long task in Javascript

查看:65
本文介绍了用Java语言执行长任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在以下代码中,我可以一次看到整个页面?谢谢!

Why in the following code I see the whole page at once ? Thanks !

HTML:

<div></div>

CSS:

div {
    width: 100px;
    height: 300px;
    border: 1px solid black;
    text-align: center;
}

JavaScript:

Javascript:

$(function() {
    for (var i=0; i<15; i++) {
        sleep(100);
        $("div").append("<span>--- " + i + " ---<br /></span>");
    }

    function sleep(milliseconds) {
        var start = new Date().getTime();
        for (var i = 0; i < 1e7; i++) {
            if ((new Date().getTime() - start) > milliseconds){
                break;
            }
        }
    }
});

推荐答案

因为Web浏览器上的Javascript是单线程的(尽管正在更改;请参阅下文),并且在(主)Javascript线程繁忙时,实际上没有浏览器会更新其UI. .您所有sleep函数所做的事情都是阻止所有内容100毫秒,它不允许浏览器执行其他任何操作,例如更新其UI(例如,不屈服").

Because Javascript on web browsers is single-threaded (although that's changing; see below) and virtually no browser updates its UI while the (main) Javascript thread is busy. All your sleep function does is block everything for 100ms, it doesn't let the browser do anything else like update its UI (e.g., doesn't "yield").

有两种方法可以完成您想做的事情:

There are a couple of ways to do what you're trying to do:

  1. 使用新的网络工作者;但请注意,它尚未得到广泛支持.

使您的循环成为通过setTimeout调用自身的函数.这样,您的代码就会屈服于浏览器并让其更新其UI.

Make your loop a function that calls itself via setTimeout. That way, your code is yielding to the browser and letting it update its UI.

这是一个简单示例,说明如何将上述第二条代码应用于代码:

Here's a simple example of how you might apply #2 above to your code:

$(function() {
    var i;

    doOne();

    function doOne() {
        $("div").append("<span>--- " + i + " ---<br /></span>");
        if (i++ < 15) {
            setTimeout(doOne, 0);   // <== Won't really be zero, browsers clamp it at ~10
        }
    }

});

如果您有很多循环迭代(例如,几百次而不是15次),则可能值得在每次迭代中进行大量的迭代,而不是在每次迭代时都屈服;产量需要一个可测量的时间(通常〜10-15ms).

If you have a lot of loop iterations (e.g., a couple of hundred instead of 15), it may well be worth doing a chunk of them on each iteration rather than yielding on each iteration; the yield takes a measureable time (typically ~10-15ms).

这篇关于用Java语言执行长任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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