【发布时间】:2015-06-01 18:48:43
【问题描述】:
我有一个长时间运行的函数,它进行大量计算:x n 面骰子的所有可能排列以及这些结果的概率。对于较小的 x 和 n,计算速度很快。对于较大的值(n = 100, x > 3),计算需要几十秒甚至更长;同时,浏览器停止。
这是我的代码的 sn-p:
let dist = [];
// min and max are the minimum and maximum possible values
// (if dice are all 1's or all their maximum values)
for (let i = min; i <= max; i++) {
// initialize possible values of our distribution to 0
dist.push([ i, 0 ]);
}
// total is the total outcome value so far
// dIndex is the index into the dice-array (diceList) for the die we're
// currently applying to our total--the die we're "rolling"
function applyDie(total, dIndex) {
if (dIndex === diceList.length) {
dist[total - min][1]++;
permutationsCount++;
return;
}
// diceList is an array of integers representing the number of sides
// for each die (one array element = one die of element-value sides)
for (let i = 1; i <= diceList[dIndex]; i++) {
applyDie(total + i, dIndex + 1);
}
}
// kick off recursive call
applyDie(0, 0);
我想添加两个功能:
- 取消
- 进度报告
一旦我有了异步模式,取消将很容易(我可以自己做),所以我真的只需要进度报告方面的帮助,或者更准确地说,只需根据 @987654323 将递归模式分解成块@ 多变的。即
/* ... */
permutationsCount++;
if (permutationsCount % chunkSize === 0)
/* end this chunk and start a new one */
我更喜欢使用 Javasciprt Promises,但我愿意接受其他建议。
想法?
【问题讨论】:
-
JavaScript 是单线程的,您要么必须使用
WebWorker(developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/…),要么只需对服务器执行工作并使用 ajax 轮询它的进度/完成情况。 -
我知道 JavaScript 是单线程的,但是使用 Promises,你可以做一些计算,并在当前运行的 Promise 中添加一个
.then(),以便在块完成后继续计算。不过,在这两者之间,浏览器可以做其他事情(事件、更新 UI 等),模仿异步行为。 -
对不起,我假设你是在客户端用JS计算,你是在服务器端计算吗?
-
不,我在客户端上做。无论如何,服务器都在 node.js 上运行,所以这无济于事。 :)
-
使用网络工作者,你的例子正是为网络工作者创建的:)
标签: javascript asynchronous recursion