问题:如何让我的 files.map(...)
每 50 次迭代暂停一次?
问题:gm().size()
是一个非常昂贵的函数。经过大约 300 次迭代后,它完全崩溃了。我有一个理论,如果我让这个功能保持下去,这个问题就会得到解决。
//interaction happens that will traverse a bunch of folder and create an array of files paths
glob(filePath + '/**/*{.png,.jpg,.gif}', function (er, files) {
var chunksize = 50; // sets the iteration size
if (er) return er;
service.stuff[name] = files.map(function (entry, i) {
return {
identity: getIdentity() //returns the identity(size) of images
};
function getIdentity() {
if(i % chunksize == 0) { // if the 50th iteration
(function(chunksize, i){
setTimeout(function () {
var entrySize = gm(entry) //graphics magic will return size of images based on path.
.size(function (err, size) {
return size;
});
}, 2000); //pause for 2 seconds.
}());
} else {
var entrySize = gm(entry)
.size(function (err, size) {
return size;
});
}
return entrySize.data; //returns identity data.
}
});
});
最佳答案
或者,实现您自己的批处理器。这种映射的替代方案一次只会处理 options.batchSize
项,然后进行 options.timeoutMs
中断以使应用程序有时间执行其他操作。
function batchMap(array, fn, options, callback) {
var batchSize = options.batchSize || 100,
timeoutMs = options.timeoutMs || 0;
function map(done, todo) {
if(todo.length > 0) {
setTimeout(function() {
var mapped = todo.slice(0, batchSize).map(fn);
map(done.concat(mapped), todo.slice(batchSize));
}, timeoutMs);
} else {
callback(null, done);
}
}
map([], array);
}
关于javascript - 如何在 array.map() 循环中每 50 次迭代设置一个超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33534163/