0

I'm trying to create a loop with a setTimeout in console log browser. But it is not working. I tried searching but have not found what I needed. Basically in each loop would be 5sec intervals during this printa 5sec in late updates. Would have to bring an array into the loop.

var myArray1 = new Array( "orange", "blue", "white" );

for (var i = 0; i <= myArray1.length; i++) {

  console.log("This fruit" + myArray1[i] + "is delcious!");

  setTimeout(function(){ alert() }, 500); //AFTER FIVE SECONDS

setTimeout(function(){
  } //CLOSE FOR
}, 5000); //AFTER FIVE SECONDS

Let me give an example that I used and it works, but the code is too large. I wanted a way to better understand loop.

var myArray1 = new Array( "orange", "blue", "white" );
var var_time = 7000;

setTimeout(function(){
  console.log("Fruit is " + myArray1[0]);
  console.log("...stage 1 loading");


  setTimeout(function(){
    console.log("Fruit is " + myArray1[1]);
    console.log( "...stage 2 loading");

    setTimeout(function(){
      console.log("Fruit is " + myArray1[2]);
      console.log( "stage 2 finish");

      alert();

      console.log( "You code run perfect");

    }, var_time); //stage 2
  }, var_time); //stage 1
}, 500); //stage 0
2
  • 1
    use 5000 * i for your timeout inside of the for loop. remember, javascript is asynchronous, so all of the setTimeouts will run at essentially the same time. Commented Jan 14, 2015 at 16:15
  • 3
    See: stackoverflow.com/questions/26380086/… Commented Jan 14, 2015 at 16:16

2 Answers 2

1

Not pretty, but simple.

var fruitColors = ["orange", "blue", "white"];

function showColor(index) {
   if (index < fruitColors.length) {
       console.log("Fruit is " + fruitColors[index]);
       setTimeout(function() { showColor(index+1); }, 500);
   }
}

setTimeout(function() { showColor(0); }, 500);

A prettier but more complicated way would be:

var fruitColors = ["orange", "blue", "white"];

fruitColors.reverse().reduce(function(m,c) {
    return function() {
       console.log("Fruit is " + c);
       setTimeout(m, 500);
    };
}, function() {})();

You can read about reduce here (MDN).

Sign up to request clarification or add additional context in comments.

3 Comments

This code violates the "Don't Repeat Yourself" principle
@Alnitak yes, but I think it's easier to understand.
The code he did was modify and use for what I wanted. Wanted to make clear that you guys helped a lot. But luckily for what I need this code already served me. Thanks. @Alnitak Not get hurt.
0

My usual code for this would be:

var myArray1 = [ "orange", "blue", "white" ];

(function loop() {
    // find first element and do something with it
    var current = myArray1.shift();
    ...

    if (myArray1.length) {
        setTimeout(loop, 5000);
    }
})();  // start immediately

This does of course mutate the array as the loop runs - take a copy if that's a problem.

A more general version is this:

function repeat(array, delay, callback, done) {
    var a = array.slice();
    (function loop() {
        var x = a.shift();
        callback(x);
        if (a.length) {
            setTimeout(loop, delay);
        } else {
            done();
        }
     })();
};

with usage:

repeat(myArray1, 5000, function(f) {
    console.log(f)
}, function() {
    console.log(done);
}

9 Comments

Why not setInterval()?
When I put console.log("This fruit " + myArray1 + " is delcious!"); he is putting twice and repeats four times and not three
you should be logging "current", not the whole of MyArray1
@IsmaelMiguel: Both are good options, but I think it is better to use setTimeout over setInterval here. Because we have a simple termination condition, you can stop the repeated calls with the simple if (current.length) {…} wrapper around the next call instead of having to keep track of a timer ID.
@IsmaelMiguel what markegli said. Also, setInterval behaves badly if timer intervals are missed.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.