Javascript将一些计算结果逐个追加到表行中
我正在开发一个简单的electron/node.js应用程序,它在本地获取输入信息,进行一些计算,并在表格中显示计算结果 输入:Javascript将一些计算结果逐个追加到表行中,javascript,html,node.js,electron,Javascript,Html,Node.js,Electron,我正在开发一个简单的electron/node.js应用程序,它在本地获取输入信息,进行一些计算,并在表格中显示计算结果 输入: 10s of rows of features info ID | length | depth | 计算:每个特征计算大约需要几秒钟 输出: Some amount of row from input, but with a results column ID | length | depth | Results 我试图将结果附加到表中以进行显示,代码如下
10s of rows of features info
ID | length | depth |
计算:每个特征计算大约需要几秒钟
输出:
Some amount of row from input, but with a results column
ID | length | depth | Results
我试图将结果附加到表中以进行显示,代码如下所示
<table id = 'results-table'>
<th>ID</th><th>length</th><th>depth</th><th>Results</th>
</table>
IDlengthdepthResults
函数getCrackTableValues(){
document.body.style.cursor='wait';
var table=document.getElementById('input-table');//从输入表获取信息
对于(var r=1,n=table.rows.length;rdocument.body.style.cursor='wait'代码>。并在所有计算完成后重新启用光标
但这一行似乎在计算后执行了,它只是禁用了光标并再次闪烁
我当前的实施是否存在任何潜在问题?My node.js是v12.16.3,在旧的32位windows 7上。这两个问题的原因是相同的:用户界面只有设法摆脱长时间运行的循环,才有机会更新
您需要将foo()
更改为异步函数。您没有显示任何详细信息,因此我将假定它是纯CPU计算,没有文件或网络访问点
我想我应该先把循环内容拉到另一个函数中。然后我将循环终止条件放在新函数的顶部:
function processOneRow(r){
const table = document.getElementById('input-table');
if(r >= table.rows.length){ //All done
document.body.style.cursor = 'default';
return;
}
const crackID = table.rows[r].cells[0].innerHTML;
const a_m = Number(table.rows[r].cells[1].innerHTML);
const c_m = Number(table.rows[r].cells[2].innerHTML);
const result = foo(a_m, c_m);
const newRow = document.getElementById('results-table').insertRow();
newRow.innerHTML = '<td>'+ ...;
setTimeout(processOneRow, 0, r+1)
}
使用带有0毫秒延迟的setTimeout()
,会给UI线程每次更新的时间,然后它会在输入表的下一行调用processOneRow()
旁白:将用于恢复光标的代码放在processOneRow()
中有点代码味道。如果这段代码放在库中,我可能会使用before()
/after()
挂钩。(如果抛出异常,还可以确保调用after()
钩子。)
另一种方法是使用并移动foo(a\m,c\m)
计算。这自然是异步的。除了额外的复杂性之外,它的缺点是如果foo()
使用数据,则需要将其保存在工作线程中,如果主线程中需要相同的数据,则会变得复杂。但是,否则,对于长时间运行的流程来说,它是一个更好的解决方案。谢谢Darren。只是想知道UI是否总是在其他运行循环完成后才能更新?即使ui命令出现在脚本中的其他命令之前。是的,始终如此,请参阅中的“运行到完成”部分(搜索有关JavaScript事件循环的文章是很好的背景阅读)
function processOneRow(r){
const table = document.getElementById('input-table');
if(r >= table.rows.length){ //All done
document.body.style.cursor = 'default';
return;
}
const crackID = table.rows[r].cells[0].innerHTML;
const a_m = Number(table.rows[r].cells[1].innerHTML);
const c_m = Number(table.rows[r].cells[2].innerHTML);
const result = foo(a_m, c_m);
const newRow = document.getElementById('results-table').insertRow();
newRow.innerHTML = '<td>'+ ...;
setTimeout(processOneRow, 0, r+1)
}
function getCrackTableValues(){
document.body.style.cursor = 'wait';
setTimeout(processOneRow, 0, 1)
}