По сути, вы хотите разделить операцию на части. Допустим, у вас есть 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.
});
Также обратите внимание, что Google Gears поддерживает работу в отдельном потоке . Firefox 3.5 также представил своих собственных сотрудников, которые делают то же самое (хотя они следуют стандарту W3 , в то время как Google Gears использует свои собственные методы.)