Về cơ bản, những gì bạn muốn làm là chia hoạt động thành từng mảnh. Vì vậy, nói rằng bạn có 10 000 mục bạn muốn xử lý, lưu trữ chúng trong một danh sách và sau đó xử lý một số lượng nhỏ trong số họ với một sự chậm trễ nhỏ giữa mỗi cuộc gọi. Đây là cấu trúc đơn giản mà bạn có thể sử dụng:
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.
});
Cũng lưu ý rằng Google Gears has support to do work on a separate thread. Firefox 3.5 cũng đã giới thiệu its own workers that do the same thing (mặc dù họ theo dõi the W3 standard, trong khi Google Gears sử dụng các phương pháp riêng của mình.)
+1, nhưng 'công nhân' bánh răng không chính xác những gì môi trường khác gọi là 'chủ đề'. – Javier
Firefox 3.5 cũng có công nhân chuẩn hóa W3. Xem câu trả lời của tôi cho các liên kết. – Blixt