如何在显示整个 UI 时开始计算

How to start computation when entire UI is shown

本文关键字:UI 开始 计算 显示      更新时间:2023-09-26

考虑最简单的情况 - 显示进度条,开始计算,关闭进度条。

有了这样的 html 片段:

<p id="hello" style="display:none">HELLO WORLD</p>  

令我惊讶的是,这不起作用:

function foo()
{
    var hello = $('#hello');
    hello.html(new Date().getTime());
    hello.show();
    setTimeout(function(){
        var big = 0;
        for (var i=0;i<10000000;++i)
            if (Math.sqrt(i)>Math.cos(i)) // just to keep CPU busy
                big = i;
        console.log(i);
    },0);
}
$(window).load(function () 
{
    foo();
});

使用 jQuery promise也无济于事:

hello.show().promise().done(function(){...

在这两种情况下,元素都会在控制台中输出的同时显示(直观)。

我直观地写了,因为在内部可以报告元素已经显示,但用户看到的内容很重要。

您可以将用于计算的代码放在单独的javascript函数中,即使它的线性它也不会等待计算在javascript中完成并立即移动到下一行。我在隐藏进度条之前等待了一段时间,因为您需要让它至少可用一秒钟。

function startComputing(){
        var big = 0;
        for (var i=0;i<10000000;++i)
            if (Math.sqrt(i)>Math.cos(i)) // just to keep CPU busy
                big = i;
        console.log(i);
}
function foo()
{
    var hello = $('#hello');
    hello.html(new Date().getTime());
    hello.show();
    setTimeout(function(){startComputing();},500);
    setTimeout(function(){hello.hide()},1000);
}