Rob*_*Rob 43 javascript multithreading
我有一个cpu密集型任务,我需要在客户端上运行.理想情况下,我希望能够使用jquery调用该函数并触发进度事件,以便我可以更新UI.
我知道javascript不支持线程,但我看到一些有希望的文章尝试使用setTimeout来模仿线程.
最好的方法是什么?谢谢.
Bli*_*ixt 38
基本上,您要做的是将操作分成几部分.因此,假设您要处理10 000个项目,将它们存储在列表中,然后在每次调用之间稍加延迟处理少量项目.这是一个你可以使用的简单结构:
function performTask(items, numToProcess, processItem) {
var pos = 0;
// This is run once for every numToProcess items.
function iteration() {
// Calculate last position.
var j = Math.min(pos + numToProcess, items.length);
// Start at current position and loop to last position.
for (var i = pos; i < j; i++) {
processItem(items, i);
}
// Increment current position.
pos += numToProcess;
// Only continue if there are more items to process.
if (pos < items.length)
setTimeout(iteration, 10); // Wait 10 ms to let the UI update.
}
iteration();
}
performTask(
// A set of items.
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'],
// Process two items every iteration.
2,
// Function that will do stuff to the items. Called once for every item. Gets
// the array with items and the index of the current item (to prevent copying
// values around which is unnecessary.)
function (items, index) {
// Do stuff with items[index]
// This could also be inline in iteration for better performance.
});
Run Code Online (Sandbox Code Playgroud)
另请注意,Google Gears支持在单独的线程上执行操作.Firefox 3.5还引入了自己的工作人员来做同样的事情(尽管他们遵循W3标准,而Google Gears使用自己的方法.)
小智 20
我最近有一个类似的问题要解决,我需要保持我的UI线程自由,同时处理一些数据显示.
我写了一个库Background.js来处理几个场景:顺序后台队列(基于WorkerQueue库),每个定时器调用每个定时器的作业列表,以及帮助将你的工作分解成更小块的数组迭代器.这里的示例和代码:https://github.com/kmalakoff/background
请享用!