【问题标题】:Editing text using innerText in for loop freezes the browser在 for 循环中使用 innerText 编辑文本会冻结浏览器
【发布时间】:2021-12-03 03:07:45
【问题描述】:

我正在尝试将页面上的元素用作进度指示器(以百分比为单位)。 但是,当我在 for 循环内调用 innerText 时,Chrome 会冻结并且不显示进度。这是示例代码(只是为了展示问题):

<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
    <meta charset="utf-8"/>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1 id="a">Hello!</h1>
</body>
<script type="text/javascript">
    function initTrs(){
        for(var i = 1; i<=100; i++){
            document.getElementById("a").innerText = i;
            $.ajax({
                url: "https://www.google.com",
                async: false,
                done: function (a) {}
            });
        }
    }
    window.addEventListener("load", () => initTrs());
</script>
</html>

Firefox 可以正常工作;但是,Chrome 会冻结,直到 for 循环完全完成。

谁能帮我解决这个问题?谢谢!

【问题讨论】:

  • 您已将 AJAX 调用指定为同步,Chrome 将其视为事件循环中的阻塞,因此在更新 innerText 之前等待循环完成。你为什么要打同步电话?
  • 我真的很想知道为什么这会在 FF 中起作用。因为当 JS 运行时,DOM 的渲染通常会被阻塞。通过强制您的ajax 调用同步执行,您不会让浏览器进行任何渲染...
  • @BenM 我的 API 需要正常工作。有没有办法在不同时发出大量请求的情况下对其进行优化?
  • @RodionGrinberg 为什么你的 API 会关心是同步还是异步调用它?
  • 使 ajax 调用异步并等待它,并使 initTrs 异步以便能够在其中使用 await。

标签: javascript html ajax


【解决方案1】:

最后我是这样解决的:

<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
    <meta charset="utf-8"/>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1 id="a">Hello!</h1>
</body>
<script type="text/javascript">
    function initTrs(){
        for(var i = 1; i<=100; i++){
            const iter = i;
            setTimeout(() => {
                document.getElementById("a").innerText = iter;
                $.ajax({
                    url: "https://www.google.com",
                    async: false,
                    done: function (a) {}
                });
            });
        }
    }
    window.addEventListener("load", () => initTrs());
</script>
</html>

【讨论】:

  • 因为您没有在 setTimeout 中设置时间跨度,所以它的超时时间为 0,并且您有 100 个并行(异步)请求。如果你的 api 没问题,你根本不需要setTimeout ...
猜你喜欢
  • 1970-01-01
  • 2017-05-20
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-21
相关资源
最近更新 更多