How to use setTimeout inside a for loop in JavaScript

How to use setTimeout inside a for loop in JavaScript

In this post we will give you information about How to use setTimeout inside a for loop in JavaScript. Hear we will give you detail about How to use setTimeout inside a for loop in JavaScriptAnd how to use it also give you demo for it if it is necessary.

we are going to learn about the how can we use setTimeout method inside a for loopin JavaScript with the help of examples.

for loop

Let’s see what happens when we add a setTimeout method inside a for loop.

for (var i=0;i<5;i++){    setTimeout(function(){        console.log(i);    }, 1000);}//---> Output  5,5,5,5,5

After 1000 milliseconds we will see a 5 is logged inside browser console but we need 0,1,2,3,4 this happens because of JavaScript is executing the code in synchronous fashion(it means one line after another) but setTimeout method is asynchronous so that JavaScript runs the asynchronous code once the synchronous code execution is completed.

At the time of synchronous code (for loop) execution is completed the variable i value is 5 so that we can see 5 inside our console.

Using let keyword

The problem can be solved by using an es6 let keyword because it creates a new variable on each iteration but var keyword is using the same variable throughout the for loop execution.

for (let i=0;i<5;i++){    setTimeout(function(){        console.log(i);    }, 1000);}// -- > output  0,1,2,3,4

Using IIFE function

If you don’t like using es6 let keyword, we can also solve the problem by using immediately invoked function expression (IIFE).

Example:

for (var i = 0; i < 5; i++) {  (function(val) {     //val is parameter    setTimeout(function() {      console.log(val);    }, 1000);  })(i); // i is argument}// -- > output  0,1,2,3,4

In the above code, on each iteration the function is invoked by itself a var i is passed an argument to the function so that we can see the expected output because on each iteration the variable i is holding a different value.

Using functions

for (var i = 0; i < 5; i++) {  function timeout(val) {    setTimeout(function() {      console.log(val);    }, 1000);  }  timeout(i);}

Hope this code and post will helped you for implement How to use setTimeout inside a for loop in JavaScript. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US