在执行功能时显示javascript加载程序图像

时间:2022-12-04 20:33:41

I want to click a button, show a loader image, execute a time-consuming function, hide the loader image. When I attempt this, the page freezes until the entire event runs, so the loader image is never seen.

我想单击一个按钮,显示一个加载器图像,执行一个耗时的功能,隐藏加载器图像。当我尝试这个时,页面冻结直到整个事件运行,因此从未看到加载器图像。

Here is a sample:

这是一个示例:

$('#btn').click(function() {
    $('#LoadingImage').show();
    <time consuming function>
    $('#LoadingImage').hide();
});

How can I distinctly show the loader image, update the screen, run the function, hide the loader image?

如何清楚地显示加载器图像,更新屏幕,运行功能,隐藏加载器图像?

2 个解决方案

#1


13  

Although what you have should work, try doing this:

虽然你有什么应该工作,试试这样做:

$('#btn').click(function() {
    $('#LoadingImage').show();
    setTimeout(function() {
        <time consuming function>
        $('#LoadingImage').hide();
    }, 0);
});

This will escape the call stack of the event.

这将转义事件的调用堆栈。

If THAT doesn't work, then post more details as to what this mystery time consuming function is.

如果这不起作用,那么发布更多关于这个神秘的耗时功能的细节。

#2


1  

For various reasons JS has to execute on the main thread, which means that painting is blocked as long as JS is executing -- even multiprocess architectures like chrome cannot repaint a tab if that tab is executing JS.

由于各种原因,JS必须在主线程上执行,这意味着只要JS正在执行,绘制就会被阻止 - 即使像Chrome这样的选项卡执行JS,像chrome这样的多进程体系结构也无法重新绘制选项卡。

Your only way to get painting to occur will be to split up execution of your function, or move the function onto an html5 worker thread -- and they only work on the betas of Firefox and Safari (or more generally any sufficiently recent build of webkit proper)

让绘画发生的唯一方法是分离你的函数的执行,或者将函数移动到html5工作线程 - 它们只适用于Firefox和Safari的beta(或更普遍的任何最新的webkit构建)正确)

#1


13  

Although what you have should work, try doing this:

虽然你有什么应该工作,试试这样做:

$('#btn').click(function() {
    $('#LoadingImage').show();
    setTimeout(function() {
        <time consuming function>
        $('#LoadingImage').hide();
    }, 0);
});

This will escape the call stack of the event.

这将转义事件的调用堆栈。

If THAT doesn't work, then post more details as to what this mystery time consuming function is.

如果这不起作用,那么发布更多关于这个神秘的耗时功能的细节。

#2


1  

For various reasons JS has to execute on the main thread, which means that painting is blocked as long as JS is executing -- even multiprocess architectures like chrome cannot repaint a tab if that tab is executing JS.

由于各种原因,JS必须在主线程上执行,这意味着只要JS正在执行,绘制就会被阻止 - 即使像Chrome这样的选项卡执行JS,像chrome这样的多进程体系结构也无法重新绘制选项卡。

Your only way to get painting to occur will be to split up execution of your function, or move the function onto an html5 worker thread -- and they only work on the betas of Firefox and Safari (or more generally any sufficiently recent build of webkit proper)

让绘画发生的唯一方法是分离你的函数的执行,或者将函数移动到html5工作线程 - 它们只适用于Firefox和Safari的beta(或更普遍的任何最新的webkit构建)正确)