0

I'm new in this thing and I don't understand why is happening. According to internet setTimeout function is supposed to run my code after the milliseconds that I choose, and it works, but why when I put it inside a for loop it just wait for once? How can I solve it? tnks

for (let i = 0; i < 5; i++) {
    setTimeout(function(){
        console.log(i);
    },1000)
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  
  <script src="js/main.js"></script>
</body>
</html>
  • 1
    because setTimeout method is asynchrone. – Mister Jojo Oct 15 '22 at 23:50
  • 1
    "_when I put it inside a for loop it just wait for once_" - It waits for all three. You schedule three timeouts, all of which run after one second. But the scheduling happens simultaneously. – Ivar Oct 15 '22 at 23:56

0 Answers0