how to slow down a javascript loop

Modern JS Solution:

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)
    }    
}

The only draw back is you have to execute the delay from inside an async function.


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?


You probably want to use a timer for this. If you would just put a delay loop in the code, the result would only be that the code takes longer to run, but the final result will show up all at once after the code has finished.

You can use the setTimeout or setInterval methods. Example:

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);

}();