gpt4 book ai didi

javascript - 将 setTimeout 与 jQuery 一起使用

转载 作者:行者123 更新时间:2023-12-02 13:49:16 24 4
gpt4 key购买 nike

我想在第一个 $.each 的每次迭代之间添加 500 毫秒的暂停

我不确定如何应用此解决方案: How to add pause between each iteration of jQuery .each()?

对于我的具体情况:

function iterateAddresses () {

var time = 500;

$.each( addresses_google, function( index, value ) {
var service = new google.maps.DistanceMatrixService();

service.getDistanceMatrix(
{
origins: [origin],
destinations: value,
travelMode: 'DRIVING'
},
callback
);

function callback(response, status) {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
for (var j = 0; j < results.length; j++) {
var element = results[j];
if(element.status == "NOT_FOUND"){
var distance = 0;
} else {
var distance = element.distance.value;
}
if(distance > radius){
// Store postids in array
postids_to_hide.push(
addresses_postids[index][j]
);
// Hide elements where postid is in the postids_to_hide arrays
$.each( postids_to_hide, function( index, value ) {
$(".main_short_post_div").filter(function(){
return $(this).attr('data-post-id') === value;
}).hide();
});
} // end if d < r
} // end for j
} // end for i
} // end callback function
}); // end each addresses_google

}; // end iterateAddresses

iterateAddresses();

最佳答案

function asyncForEach(arr, cb) {
return arr.reduce((p,c)=>{
return p.then(()=>cb(c));
}, Promise.resolve());
}
function wait(ms) {
return ()=>new Promise(resolve=>setTimeout(resolve, ms));
}

const DELAY = 500; //ms
function iterateAddresses() {
return asyncForEach(addresses_google, address =>
getDistanceMatrix(address)
.then(processResult)
.then(wait(DELAY)));
}

iterateAddresses();

getDistanceMatrix 是您提供给 $.each 的函数的 promise 版本。

processResultcallback 的 promise 版本。

关于javascript - 将 setTimeout 与 jQuery 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41130875/

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