gpt4 book ai didi

javascript - 如何在 array.map() 循环中每 50 次迭代设置超时?

转载 作者:搜寻专家 更新时间:2023-11-01 00:41:18 24 4
gpt4 key购买 nike

问题:如何让我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com