how to slow down a javascript loop

前端 未结 5 1123
执念已碎
执念已碎 2021-01-04 10:59

I would like a add a 1-2 second delay on each iteration of the following loop.




        
5条回答
  •  春和景丽
    2021-01-04 11:38

    You can do it this way with 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;
        });          
    }); 
    

    This does make me wonder why you're doing a geocode lookup on the exact same address 20 times in a row?

提交回复
热议问题