9

I want to delay a "for loop" for a while but don't know how to do it.

For example. Let's say this "for loop" runs from 0 to 8 and after each i there should be a delay for 2 sek.

for (var i=0; i<8; i++{
  do something...
  wait for 2 sek. and go on with i=i++;
}
Linda
  • 2,375
  • 4
  • 30
  • 33
  • 1
    Can you give the details of what you're actually trying to achieve? It's likely that you'll want to use setTimeout but it's hard to say without knowing your aim. – DoctorMick Dec 12 '14 at 12:00
  • 1
    That's not possible in JS. You have to play with functions and use `setTimeout`. – Teemu Dec 12 '14 at 12:00
  • 3
    I guess that this thread answers what you are asking for http://stackoverflow.com/questions/3583724/how-do-i-add-a-delay-in-a-javascript-loop – Pedro Coutinho Dec 12 '14 at 12:01

3 Answers3

12

You'll have to go that way:

function jsHello(i) {
    if (i < 0) return;

    setTimeout(function () {

        alert("Hello " + i);

        jsHello(--i);

    }, 2000);
}

jsHello(5);

or

function jsHello(i) {
    alert("Hello " + i);

    if (--i > -1) {
      setTimeout(function () { jsHello(i); }, 2000);
    }
}

jsHello(5);
metadings
  • 3,798
  • 2
  • 28
  • 37
5

Javascript doesn't have a wait command. The way to get this behavior is using setTimeout:

for (var i=0; i<8; i++){
   do_something(i);
}

function do_something(j) {
  setTimeout(function() {
      tasks to do;
  }, 2000 * j);
}

Every time the function do_something() is called, it executes "tasks to do" scheduled by 2000*i milliseconds.

Evgeniy
  • 2,915
  • 3
  • 21
  • 35
jcbermu
  • 557
  • 6
  • 12
3

To resolve this task you have to use closure - immediately invoke function witch be called on every iteration with i as param, and setTimeout inside this function. In this case param you passed will be stored in scope and could be used in timeout callback:

for (var i=0; i<8; i++) (function(t) {
  window.setTimeout(function() {
   //do anything with t 
  }, t*2000)
}(i)) 

UPD

Also here is a shorten ES6 version. As let has block scope you can get rid os wrap function closure use

for (let i=0; i<8; i++){
   setTimeout(() => {
      console.log(i)
  }, 2000 * i);
}
Evgeniy
  • 2,915
  • 3
  • 21
  • 35