我有一个电子应用程序,其中单击一个按钮即可运行挖掘功能,这需要很长时间才能运行。我正在尝试显示随机数,因为它在页面上作为元素更改。但是,当我运行该功能时,页面会冻结,并且仅在该功能完成后才会更改。
//Mining function
function mine(index, time, prev, transactions, difficulty) {
if (index !== 0) {
this.log(`Mining Block ${index}`);
}
const startTime = Date.now();
let nonce = 0;
let hash = '';
while (hash.substring(0, difficulty) !== Array(difficulty + 1).join('0')) {
nonce++;
hash = crypto
.createHash('sha256')
.update(
index.toString() +
time.toString() +
prev.toString() +
transactions.toString() +
nonce.toString()
)
.digest('hex')
.toString();
//Nonce indicator
$("#nonce").text(`Nonce: ${nonce}`);
}
const performanceTime = Date.now() - startTime;
if (performanceTime <= 60000 && index !== 0) {
this.difficulty++;
this.log(`Difficulty Increased. Difficulty Is Now ${this.difficulty}`);
}
const seconds = performanceTime / 1000;
const performance = Math.floor((10 * nonce) / seconds) / 10000;
if (index !== 0) {
if (performance !== Infinity && performance >= 25) {
this.log(`Performance: ${performance} kh/s`);
$("#performance").text(`Performance: ${performance} kh/s`);
} else {
this.log(`Performance Could Not Be Measured`);
$("#performance").text(`Performance: Error`);
}
this.log(`Block ${index} Successfully Mined`);
}
return nonce;
}
//Call
function mineHandler(){mine(props)}
$("#miningBtn").click(mineHandler);
答案 0 :(得分:0)
这是浏览器的工作方式。 (Electron的显示实际上是浏览器。)只有一个线程负责更新UI和运行客户端JavaScript代码。 (在Electron中,它是“渲染线程”。)因此,当您的JavaScript代码运行时,UI不会更新。
有两种解决方案:
让另一个线程进行繁重的工作,并定期将更新发布到主线程。在浏览器中,您可以使用web worker来实现。显然,您也可以让Web工作者使用Electron,请参阅this example。或者,也许您可以由主要过程完成工作,而不是由渲染过程完成。
破坏逻辑,以便定期让浏览器返回浏览器,以便它有机会更新其显示。
#1可能是您进行数字运算时最好的选择。这是一个示例,从1到1,000,000,000,每10,000更新一次:
// Get the contents of our worker script as a blob
var workerScript = document.getElementById("worker").textContent;
var blob = new Blob(
[workerScript],
{
type: "text/javascript"
}
);
// Create an object URL for it
var url = (window.webkitURL || window.URL).createObjectURL(blob);
// Start the worker
var worker = new Worker(url);
worker.addEventListener("message", function(e) {
if (e && e.data && e.data.type === "update") {
display.textContent = "Value: " + e.data.value;
}
});
<script id="worker" type="javascript/worker">
// The type on this script element means the browser
// won't run it directly. It's here so we can turn it
// into a blob to run the worker later.
for (var n = 1; n <= 1000000000; ++n) {
if (n % 10000 === 0) {
self.postMessage({type: "update", value: n});
}
}
</script>
<div id="display">Waiting for worker to start...</div>