Delay Javascript

Asked

Viewed 6,045 times

2

I need to spin a loop for every 2 seconds, as I can do ?

for(var i = 0; i <= 5; i++)
{    				
   console.log(i);                    
}

2 answers

1

Using the function setInterval you can do it that way too:

let i = 0

const timer = setInterval(function() {
  if (i >= 5) {
    // aborta a execução caso a condição seja atingida
    clearInterval(timer)
  }

  i++
  console.log(i)
}, 2000)

0

You can use the setInterval:

function repeticao() {
  for (var i = 0; i <= 5; i++) {
    (function loop(i) {
      setTimeout(function() {
        console.log(i);
      }, 2000*i)
    })(i);
  }
}

repeticao();

  • So, I need the delay only in FOR because the function will be called by means of a button. There is another way friend ?

  • Delay between each loop of for?

  • Exactly, I need to call a single time the function and the FOR loop loop every x time until the FOR loop is finished.

  • I edited the reply @Robotrol

Browser other questions tagged

You are not signed in. Login or sign up in order to post.