//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();
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();
0 Comments