gpt4 book ai didi

javascript - 如何减慢 JavaScript 循环

转载 作者:可可西里 更新时间:2023-11-01 02:35:19 26 4
gpt4 key购买 nike

我想在以下循环的每次迭代中添加 1-2 秒的延迟。

<html>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

<input id="start" type="submit"> </input>
<div id='status'></div>

<script>
var geocoder=new google.maps.Geocoder();
var glGeocodeCount = 0 ;

$(document).ready(function() {

$('#start').click(function() {

//srPerformGeocode("TD Tower, 55 King Street West, Toronto, ON, Canada, M5K 1A2");

for(x=0;x<20;x++){
srPerformGeocode("TD Tower, 55 King Street West, Toronto, ON, Canada, M5K 1A2");
}
return false;
});
});

function srPerformGeocode(address){
if (geocoder){
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK){
$('#status').prepend("Success : " + address + "<br/>");

}
else{
$('#status').prepend("Failed : " + address + "<br/>");

}
});
}
}
</script>

最佳答案

你可以用 setTimeout() 这样做:

$(document).ready(function() {
$('#start').click(function() {
//srPerformGeocode("TD Tower, 55 King Street West, Toronto, ON, Canada, M5K 1A2");
var x = 0;

function go() {
srPerformGeocode("TD Tower, 55 King Street West, Toronto, ON, Canada, M5K 1A2");
if (x++ < 20) {
setTimeout(go, 2000);
}
}
go();

return false;
});
});

这确实让我想知道为什么您要连续 20 次对完全相同的地址进行地理编码查找?

关于javascript - 如何减慢 JavaScript 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9090750/

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