Javascript - 如何防止嵌套 For 循环期间阻塞?

标签 javascript performance

我的脚本中有一组嵌套的 For 循环(普通 javascript,没有 jquery),它们可能会持续很长一段时间(30 秒以上)。在此期间,浏览器显然没有响应,并且 DOM 没有更新,因为循环被阻塞 - 正如人们所期望的那样。

在嵌套的 For 循环内,我调用另一个函数并生成一个 SVG 圆,并传递参数,然后将圆添加到 svg 元素并返回循环。

问题:可以使用什么策略来更新 DOM 并实际显示正在创建的一些 SVG 圆圈?

关于 S/O 有很多问题要求类似的解决方案,但大多数示例都使用 setTimeout(function, 0),尽管我尝试过使用它,但 DOM 不会更新,可能是因为我没有确定我应该为哪个函数设置超时?

我还发现了一些网络 worker 的示例,但无法完全理解如何在这个项目中实际使用它们。

使用这个基本示例 - 有人可以告诉我如何在循环处理时更新 DOM 吗?


<button onclick="randomCircles()">
  make circles
</button>
<svg 
  id="cont" version="1.1" 
  xmlns="http://www.w3.org/2000/svg" 
  xmlns:xlink="http://www.w3.org/1999/xlink" 
  x="0" y="0" viewBox="0, 0, 900, 600">
  <style>svg { background-color: black;}</style>
</svg>


<script>
    function randomCircles(){
        var x_end = 900;
        var y_end = 675;
        for(x=0; x<=x_end; x += 5){
            for(y=0; y<=y_end; y += 5){
                var new_circle = Math.random();
                         drawCircle(x,y,new_circle);
            }
        }
    }

  function drawCircle(x,y,circle_radius){
    var svgns = "http://www.w3.org/2000/svg";
    var container = document.getElementById('cont');
    var circle = document.createElementNS(svgns, 'circle');
    var circle_to_draw = circle_radius * 2;
    circle.setAttributeNS(null, 'cx', x);
    circle.setAttributeNS(null, 'cy', y);
    circle.setAttributeNS(null, 'r', circle_to_draw);
    circle.setAttributeNS(null, 'style', 'fill: white; stroke: none;' );
    container.appendChild(circle);

    return;
  }
</script>

非常基本的示例( fiddle :https://jsfiddle.net/wx67uyzv/2/)

这是一个更新的解决方案,感谢 Joel!

https://jsfiddle.net/198znrc0/

最佳答案

您将需要使用setInterval() .

// sample values
var loopSpeed = 25;  // How often the window will refresh, in milliseconds
var loopEnd = 75;
var loopStart = 5;
var loopIncrement = 5;


var i = loopStart;
var intervalId = setInterval(() => {

    if (i === loopEnd) {
      // wrap up
      clearInterval(intervalId);
      return;
    }

    // do loop stuff
    i += loopIncrement;

}, loopSpeed);

关于Javascript - 如何防止嵌套 For 循环期间阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57401805/

相关文章:

Java Collection-ArrayList 和 Vector 之间的加速

windows - Windows 应用程序的性能分析。 Visual Studio Profiler 的更好替代品?

ios - CIImage 和 CIFilter 实现细节

javascript - _gaq.push 没有出现在 Google Analytics 中

javascript - 带有验证和隐藏字段值的提交按钮

javascript - Java Nashorn 存储函数

javascript - 如何更改 javascript 中的值数组顺序? ['a' , 'b' ] 到 ['b' , 'a' ]

.NET/Visual Studio 中的 Javascript 测试结构

javascript - 逗号分隔的属性与带下划线或 Lo-Dash 的实际属性

Python字符串搜索效率