我的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>
答案 0 :(得分:5)
Javascript在与UI相同的线程中运行,因此您需要为DOM提供控制权以重新绘制所有更改。
答案 1 :(得分: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
}
}
});
});
您还可以在图纸之间设置TimeTime:
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)