Search code snippets, questions, articles... Chrome Extension

Stop loop for some seconds in Javascript

There are several ways to add some delay or stop loop for some seconds using Javascript. We are implementing them using recursion and ES7 await keyword.
//Using recursion function
var counter = 0;

function loop_func() {
    setTimeout(function () {
        console.log('Loop Iteration: ' + counter);
        if (counter < 4) {
            loop_func();
        }
        counter++;
    }, 2000); //Add delay here - 2000 = 2 seconds
}

// The loop will run 5 times
loop_func();
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool
Output
Loop Iteration: 0
Loop Iteration: 1
Loop Iteration: 2
Loop Iteration: 3
Loop Iteration: 4

In the above code snippet, we have created a function named loop_func() which will console some message every time it runs. Also, added is a setTimeout() Javascript function that runs every 2 seconds and runs loop_func() recursively. How many times the loop_func() will be executed, will be decided by counter variable. It is starting from 0 and will be incremented by 1 every time loop_func() executes.

Live Demo

// Returns a Promise after some seconds(provided as parameter ms)
const delay_func = ms => new Promise(res => setTimeout(res, ms))

async function loop_func() { //Create async function to use await inside it
    for (var i = 0; i < 5; i++) {
        console.log(i);
        await delay_func(2000); // this will stop the loop for 2 seconds
    }
}

loop_func();
Create an asynchronous function loop_func() and use for loop inside it. Create a delay_func() which will return a promise after 2 seconds. When we call delay_func() with await keyword before it. It will wait for the response from delay_func() then executes further. In this way, we can add some delay in for loop.
Was this helpful?
0 Comments
Join Devsheet Ask a Question