0

I want to hold the iteration of the for-loop until the functionality in the previous iteration gets completed. I have seen many questions about setTimeout but none of them has satisfied my requirement. Can anyone help me?

function abcd() {
    var exArray = [0, 0, 1, 1, 1, 0, 0, 0];
    var index = 0;
    for (var i = 0; i < exArray.length; i++) {
        if (exArray[i] == 1) {
            addDelay(++index);

        } else {
            console.log('ended at ' + i);
        }
    }
}

seTimeout functionality is something like this

function addDelay(index) {
    setTimeout(function() {
        console.log("in Timeout loop:" + index);
    }, 2000 * index);
}

The expected output is

ended at 0

ended at 1

in Timeout loop:{{index}} // wait for delay

in Timeout loop:{{index}} // wait for delay

in Timeout loop:{{index}} // wait for delay

ended at 5

ended at 6

ended at 7

But output I see in my console is:

ended at 0

ended at 1

ended at 5

ended at 6

ended at 7

in Timeout loop:{{index}} // wait for delay

in Timeout loop:{{index}} // wait for delay

in Timeout loop:{{index}} // wait for delay

I want the ended at 5 to wait until timeout functionality of 3rd, 4th, 5th array indices. I need someone to help me on this. Thanks in advance.

2
  • your setTimeout code section is well written... try a ES6 approach: setTimeout(() => { console.log('waiting 1 second...'); }, 1000); Commented Oct 30, 2017 at 12:40
  • 1
    The setTimeout will schedule a background task and then return immediately. so your loop continues to run and after the delay the timeout function is executed, so it can't work like that. The best solution in your case might be to get rid of the for loop and replace it by a callback-loop, so after each delayed execution it call the "loop" with the next index until the end of your array. Commented Oct 30, 2017 at 12:40

3 Answers 3

1

setTimeOut doesn't work that way. It just registers an action to be performed at a later point of time and just continues. Once this script is over, it will take up your queued up tasks and perform.

Check how setTimeout really works under the hood. Also, read more about JavaScript's Event Loop.

var input = [0, 0, 1, 1, 1, 0, 0, 0];

function immediateOrRegister(index) {
    if (index >= input.length) return;
    if (input[index] == 0) {
        console.log("No delay");
        immediateOrRegister(index + 1);
    } else if (input[index] == 1) {
        console.log("Timing out for atleast " + 2 * index + " seconds");
        setTimeout(function() {
            immediateOrRegister(index + 1)
        }, 2000 * index);
    }
}

immediateOrRegister(0);
Sign up to request clarification or add additional context in comments.

Comments

0

Hope I understand your question, please see this Fiddle. https://fiddle.jshell.net/qw6qp7pm/1/ (Using Underscore JS delay() http://underscorejs.org/#delay)

function abcd(index) {
  var exArray = [0, 0, 1, 1, 1, 0, 0, 0]
  var index = index ? index : 0
  if (index >= exArray.length) return false

  for (var i = index; i < exArray.length; i++) {
    if (exArray[i] == 1) {
      //addDelay(++index);
      _.delay(log, 2000, i)
      break
    } else {
      console.log('ended at ' + i)
    }
  }
}

function log(index) {
  console.log("in Timeout loop:" + index)

  // RECURSE
  abcd(index + 1)
}

abcd()

Comments

0

loop will execute continuously for its each index. as you need all your logs one-after-one, means you have to put delay for each index, whether its satisfy your condition or not.

function abcd() {  
    var exArray=[0,0,1,1,1,0,0,0];
    var index=0;
    var message='';
    for(var i=0;i<exArray.length; i++)    {
        if(exArray[i]==1) {
           ++index;
           message='in Timeout loop:'+i;
           addDelay(index, message);
        }else{
           message='ended at '+i;
           addDelay(index, message);
        }

    }
}


function addDelay(index, message){
    setTimeout(function () {
         console.log(message);
    }, 2000*index); 
}

Comments

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.