如何在正常函数调用之前显示某些内容而不是在之后停止显示?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在正常函数调用之前显示某些内容而不是在之后停止显示?相关的知识,希望对你有一定的参考价值。

我想在正常功能运行时显示加载图像(需要一段时间)

例如

function(){
    element.style.display = 'block';
    functionThatTakesAWhile()
    element.style.display = 'none';
}

我的问题是我从未看到过该元素。

-谢谢。

答案

给浏览器一个机会,在调用functionThatTakesAWhile之前呈现更改的显示。首先调用requestAnimationFrame,它将在浏览器重新绘制之前立即运行,并在其内部设置一个超时,该超时将在浏览器重新绘制之后立即运行。在该超时内,运行昂贵的函数:

const functionThatTakesAWhile = () => {
  for (let i = 0; i < 2e9; i++);
};

console.log('script start');
// Make sure page is loaded fully first, just for the sake of this example
setTimeout(() => {
  element.style.display = 'block';
  console.log('element set to block');
  window.requestAnimationFrame(() => {
    // This callback will run just before the browser paints and displays the element
    setTimeout(() => {
      // By this time, the browser will have painted the element, so you can call the expensive function
      functionThatTakesAWhile()
      element.style.display = 'none';
      console.log('element set to none');
    });
  });
}, 2000);
content
<div id="element" style="display: none">element</div>

以上是关于如何在正常函数调用之前显示某些内容而不是在之后停止显示?的主要内容,如果未能解决你的问题,请参考以下文章