是否可以强制浏览器立即从JavaScript执行回流和重绘,即使有其他代码正在运行?
我正在渲染一个进度条,一切都基于异步事件,所以当从服务器或缓存加载一些东西时,DOM会更新,但有时进度条静止在10%,那么它就会被常规的DOM文档取代。
我用display/visibility none/hidden、getComputedStyle、requestAnimationFrame尝试了所有这些技巧,但都没有强制浏览器进行真正的重绘。它可能会刷新队列并应用所有更改,但不会真正重新绘制到屏幕。
发布于 2017-01-31 05:50:42
JavaScript在单线程执行环境中运行。所以,你不能停止一个正在运行的执行上下文,然后做其他的事情。
以下面的代码片段为例。在警告出现之前,段落的文本会更新吗?
function foo(){
// Note that this timer function is set to run after a zero millisecond delay
// which effectively means immediately. But, it won't do that because it must
// first finish executing the current function. So, the timer function will be
// placed in the event queue and will run as soon as the JS engine is idle. But,
// we can't know exactly when that will be, we can only ask to run the code after
// a "minimum" delay time.
setTimeout(function(){
document.querySelector("p").textContent = "I've been updated by JS!";
}, 0);
// The alert will run before the setTimeout function because the alert is part of the
// current execution context. No other execution context can run simultaneously with this one.
alert("While you are looking at me, check to see if the paragraph's text has changed yet.");
}
document.querySelector("button").addEventListener("click", function(){
foo();
});<button>Click Me</button>
<p>Some content that can be updated by JS</p>
发布于 2017-01-31 21:06:28
因此,最终,setTimeout(resolvePromise(...),0)起到了作用。它给了浏览器一些重新绘制的时间。
https://stackoverflow.com/questions/41945963
复制相似问题