3

我的eval()电话相当密集,生成每个解决方案大约需要一秒钟。

因此生成每个段落元素大约需要一秒钟(然后我将其附加到 dom - document.getElementById('project_euler_solutions').appendChild(p); )。

因此,我希望每个段落出现在网页上大约相隔一秒钟。(所以大约 40 秒后我会说 40 段)。

但是,当我单击按钮时,40 秒内什么都没有发生,然后所有解决方案同时出现。

为什么在更新 dom 之前要等待所有这些都完成?

我认为每个段落一旦附加到 dom 就会出现

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js"></script>
    <script src="/statics/project_euler.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("button").click(function(){
                for (var i in window) {
                    if (i.slice(0,5) == "solve") {
                        var p = document.createElement('p');
                        p.innerHTML = "running: " + i;
                        document.getElementById('project_euler_solutions').appendChild(p);
                        var p = document.createElement('p');
                        p.innerHTML = "Solution: " + eval(i + "()");
                        document.getElementById('project_euler_solutions').appendChild(p);
                    }
                }
            });
        });
    </script>
</head>

<body>
<div id="project_euler_solutions"><button>Calculate solutions</button></button></div>
</body>
</html>
4

2 回答 2

5

Javascript 与 UI 在同一线程中运行,因此您需要将控制权交还给 DOM 以重新绘制所有更改。

于 2012-06-06T04:02:05.160 回答
1

强制回流:

    $(document).ready(function(){
        $("button").click(function(){
            for (var i in window) {
                if (i.slice(0,5) == "solve") {
                    var p = document.createElement('p');
                    p.innerHTML = "running: " + i;
                    document.getElementById('project_euler_solutions').appendChild(p);
                    var p = document.createElement('p');
                    p.innerHTML = "Solution: " + eval(i + "()");
                    document.getElementById('project_euler_solutions').appendChild(p);
                    document.getElementById('project_euler_solutions').offsetHeight; //Force a reflow
                }
            }
        });
    });

您还可以在图纸之间设置Timeout:

    var keys = Object.keys(window).filter(function(i){
        return i.slice(0,5) === "solve";
    });

    (function (i){
        (function k(){
            var p = document.createElement('p');
            p.innerHTML = "running: " + keys[i];
            document.getElementById('project_euler_solutions').appendChild(p);
            var p = document.createElement('p');
            p.innerHTML = "Solution: " + eval(keys[i] + "()");
            document.getElementById('project_euler_solutions').appendChild(p);
            if( i++ < keys.length - 1 ) {
                setTimeout(k, 0);
            }            
        })()
    })(0)
于 2012-06-06T04:05:00.317 回答