How to use setTimeout inside a for loop using function in JavaScript

1 Answer

0 votes
for (let i = 0; i < 8; i++) {
  function timeout(n) {
    setTimeout(function() {
      console.log(n);
    }, 2000);
  }
  timeout(i);
}



/*
run:

0
1
2
3
4
5
6
7

*/

 



answered May 22, 2021 by avibootz

Related questions

1 answer 138 views
3 answers 218 views
1 answer 133 views
1 answer 102 views
1 answer 234 views
1 answer 164 views
...