gpt4 book ai didi

javascript - UI线程是否优先于网络 worker ?

转载 作者:行者123 更新时间:2023-11-30 14:39:48 26 4
gpt4 key购买 nike

如果我在 Web Worker 中进行了数秒长的计算,我是否可以期望 UI 不会因此卡顿?包括手机?如果没有,我该怎么办?工作负载很容易分成更小的 block ,但大约一半的站点在计算完成之前无法工作。

最佳答案

...can I expect the UI to not stutter because of it?

在浏览器和设备的能力范围内,在很大程度上,是的,您可以。毕竟,这是网络 worker 的存在理由:将长时间运行的进程移出 UI 线程,以便 UI 可以保持响应。没有任何保证,但是……根据经验:我做过测试,其中工作人员在主 UI 更新时忙循环 30 秒以上,它在桌面、Android 和 iOS 上运行良好。

这样的测试并不难:

Live on plnkr

实时片段(由于我创建工作人员的方式,可能无法在所有设备上运行):

const chars = "|/-\\".split("");
let charindex = -1;
const spinner = document.getElementById("spinner");
setInterval(() => {
charindex = (charindex + 1) % chars.length;
spinner.innerHTML = chars[charindex];
}, 50);
function log(msg) {
const p = document.createElement("pre");
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}
function main() {
const url = URL.createObjectURL(
new Blob([
document.getElementById("worker").textContent
], {type: "text/javascript"})
);
const w = new Worker(url);
w.onmessage = function(event) {
if (event.data === "ready") {
w.postMessage("start");
} else {
log(event.data);
}
};
}
main();
<div id="spinner"></div>
<script id="worker" type="worker">
this.addEventListener("message", e => {
if (e.data === "start") {
let last = Date.now();
const stop = last + 20000;
let now;
while ((now = Date.now()) < stop) {
if (now - last > 1000) {
postMessage("tick");
last = now;
}
}
}
});
postMessage("ready");
</script>

worker.js:

this.addEventListener("message", e => {
if (e.data === "start") {
let last = Date.now();
const stop = last + 30000;
let now;
while ((now = Date.now()) < stop) {
if (now - last > 1000) {
postMessage("tick");
last = now;
}
}
}
});
postMessage("ready");

host.html:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Worker Host</title>
<style>
body {
font-family: sans-serif;
}
</style>
</head>
<body>
<div id="spinner"></div>
<script>
const chars = "|/-\\".split("");
let charindex = -1;
const spinner = document.getElementById("spinner");
setInterval(() => {
charindex = (charindex + 1) % chars.length;
spinner.innerHTML = chars[charindex];
}, 50);
function log(msg) {
const p = document.createElement("pre");
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}
function main() {
const w = new Worker("worker.js");
w.onmessage = function(event) {
if (event.data === "ready") {
w.postMessage("start");
} else {
log(event.data);
}
};
}
main();
</script>
</body>
</html>

关于javascript - UI线程是否优先于网络 worker ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49839861/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com