Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delay a for loop with javascript [duplicate]

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++;
}
like image 877
Linda Avatar asked Dec 12 '14 11:12

Linda


2 Answers

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);
like image 76
metadings Avatar answered Oct 21 '22 07:10

metadings


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.

like image 42
jcbermu Avatar answered Oct 21 '22 07:10

jcbermu