首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript -浏览器立即重排和重绘

JavaScript -浏览器立即重排和重绘
EN

Stack Overflow用户
提问于 2017-01-31 05:47:39
回答 2查看 860关注 0票数 1

是否可以强制浏览器立即从JavaScript执行回流和重绘,即使有其他代码正在运行?

我正在渲染一个进度条,一切都基于异步事件,所以当从服务器或缓存加载一些东西时,DOM会更新,但有时进度条静止在10%,那么它就会被常规的DOM文档取代。

我用display/visibility none/hidden、getComputedStyle、requestAnimationFrame尝试了所有这些技巧,但都没有强制浏览器进行真正的重绘。它可能会刷新队列并应用所有更改,但不会真正重新绘制到屏幕。

EN

回答 2

Stack Overflow用户

发布于 2017-01-31 05:50:42

JavaScript在单线程执行环境中运行。所以,你不能停止一个正在运行的执行上下文,然后做其他的事情。

以下面的代码片段为例。在警告出现之前,段落的文本会更新吗?

代码语言: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();
});
代码语言:javascript
复制
<button>Click Me</button>
<p>Some content that can be updated by JS</p>

票数 0
EN

Stack Overflow用户

发布于 2017-01-31 21:06:28

因此,最终,setTimeout(resolvePromise(...),0)起到了作用。它给了浏览器一些重新绘制的时间。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41945963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档