DOM样式更改等待暂停 [英] DOM style change waiting for pause
问题描述
调用此函数时,在"lotsOfProcessing()"完成之前,"gif"元素上的样式更改不会显示.但是,当我取消注释alert("test")时,将在警报弹出之前显示样式更改.
When this function is called, the style change on the "gif" element does not show up until "lotsOfProcessing()" finishes. However, when I uncomment the alert("test"), the style change is shown before the alert pops up.
我想做的是在lotsOfProcessing运行时显示动画gif.这似乎是很简单的解决方案,但显然不起作用.有什么建议/解决方案吗?
What I am trying to do is have an animated gif displayed while lotsOfProcessing is running. This seemed pretty straight forward solution but it is clearly not working. Any suggestions / solutions?
function nameOfFuntion()
{
document.getElementById("gif").style.display = "inline";
//alert("test");
lotsOfProcessing();
}
推荐答案
JavaScript代码在与浏览器呈现相同的线程上执行.所有需要绘制的内容都在等待JavaScript执行完成-包括所有GIF动画的下一帧.
JavaScript code executes on the same thread as the browser's rendering. Everything that needs to be drawn waits for JavaScript execution to complete - including the next frame of any GIF animation.
唯一的解决方案是将您的长处理代码分解为较小的部分,并使用计时器延迟每个部分.
The only solution is to break your long processing code down into smaller parts and delay each part using timers.
例如:
function nameOfFuntion() {
document.getElementById("gif").style.display = "inline";
//alert("test");
lotsOfProcessing();
}
function lotsOfProcessing() {
var i = 0;
window.setTimeout(function () {
partOfIntenseProcessing();
if (i < 1000000)
i++, window.setTimeout(arguments.callee, 10);
}, 10);
}
这将延迟您完成处理所需的时间,但是在计时器执行之间,GIF可以继续进行动画处理.
This will delay how long it will take for your processing to complete, but between timer execution the GIF can continue to animate.
您还可以查看 Web Workers ,它使您可以在背景线程.但是,它们尚未得到广泛实施(阅读:Internet Explorer中不可用).
You can also take a look at Web Workers, which allow you to run JavaScript operations in a background thread. However, they are not widely implemented yet (read: not available in Internet Explorer).
这篇关于DOM样式更改等待暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!