如何减慢javascript循环速度

时间:2012-02-01 04:21:22

标签: javascript loops

我希望在以下循环的每次迭代中添加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>

6 个答案:

答案 0 :(得分:12)

您可以使用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次在完全相同的地址上进行地理编码查找?

答案 1 :(得分:4)

您可能想要使用计时器。如果您只是在代码中放置一个延迟循环,结果只会是代码运行时间较长,但最终结果将在代码完成后立即显示出来。

您可以使用setTimeout或setInterval方法。例如:

function(){

var instructions = [
function() { /* do something */ },
function() { /* do something */ },
function() { /* do something */ },
function() { /* do something */ }
];

var index = 0;

var handle = window.setInterval(function() {
if (index < instructions.length) {
  instructions[index++]();
} else {
  window.clearInterval(handle);
}
}, 10);

}();

答案 2 :(得分:1)

我最终为此使用了模数运算符。然后你可以增加/减少它除以增加/减少延迟时间的数量。不过如果没有 for 循环可能会更好。

$(document).ready(function() {

    $('#start').click(function() {
      
        var delay = 0;
        for(x=0;x<20;x){
            delay++;
            if (delay % 10 == 0) {
                srPerformGeocode("TD Tower, 55 King Street West, Toronto, ON, Canada, M5K 1A2");
                x++;
            }
        }
        return false;
    });          
}); 

答案 3 :(得分:0)

我鼓励摆脱循环并使用setTimeout:

    $('#start').click(function() {
        var i = 0, max = 20, delay = 2000, run;
        run = function(){
           srPerformGeocode("TD Tower, 55 King Street West, Toronto, ON, Canada, M5K 1A2");
           if(i++ < max){
              setTimeout(run, delay);
           }
        }
        run();
        return false;
    });

答案 4 :(得分:0)

我有一种感觉,你宁愿不开始下一次循环迭代,直到地理编码查找真正完成。所以,关键字有“回调”:

而不是for...,请执行以下操作。我知道这可能不是你习惯的东西,但请尽量把握它(它应该有用)。

var dogeo = function(callback)
{
    srPerformGeocode("address", callback);
};

var counter = 0;

var geoCallback = function()
{
         counter++;

         if(counter < 20)
         {
             dogeo(geoCallback);
         }

};


dogeo(geoCallback);



function srPerformGeocode(address, callback){     
    if (geocoder){                
        geocoder.geocode({ 'address': address }, function (results, status) {    


           // this function is a callback of geocode()

            if (status == google.maps.GeocoderStatus.OK){                                                                                                                                                                           
                $('#status').prepend("Success : " + address + "<br/>");

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

            }

            callback(); // let the caller know this is done
        });
    }
}

答案 5 :(得分:0)

现代JS解决方案:

function timeout(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
}

async function slowedCode() {
    console.log("Before Delay")
    await this.timeout(Math.random() * 2000 + 500) // Wait random amount of time between [0.5, 2.5] seconds
    console.log("After Delay")
}

async function slowedForLoop() {
    const data = ["1","2","3","4","5"]
    for (let d of data) {
        console.log(d)
        await this.timeout(Math.random() * 100 + 500)
    }    
}

唯一的缺点是您必须从异步函数内部执行延迟。