0
for (var i = 0; i <= 2; ++i) {
    display_para(i);
};

function display_para(i){

    setInterval(function(){
        console.log(i);

        //Stuff to be done

    }, 1500 + i * 2000);
};


Expected result:
0 1 2 ; 0 1 2; 0 1 2 and so on.

Whereas it is showing different output as shown in the screenshot.

enter image description here

I could not understand where am I going wrong.

1
  • 3
    every 1.5 seconds, 0 will be output. every 3.5 seconds a 1, and every 5.5 seconds a 2 ... the timings are independent of each other (i.e. one interval doesn't wait for another Commented Jan 22, 2016 at 4:22

4 Answers 4

1

That is because how you have setup the timers, the 0 call will execute in every 1500ms, 1 call in every 3500ms and 2 call in every 5500ms.

One solution is to use a single inteval where based on a counter you decide the value to be printed like

var i = 0;
setInterval(function() {
  display_para(i);
  if (++i > 2) {
    i = 0;
  }
}, 1500);

function display_para(i) {
  document.body.innerHTML += i + '<br />'
};

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

Comments

1

You probably need this:

 var i = -1;

 setInterval(function() {
   i = i > 1 ? 0 : ++i;
   console.log(i);
 }, 1500)

Comments

1

You can't expect 0 1 2 in a sequence because there are three setInterval() running simultaneously in a different time interval. It's only possible if time interval is uniform like:

function display_para(i) {
        setInterval(function () {
            console.log(i);
        }, 200);
};

Comments

1

The for loop expands to:

display_para(0);
display_para(1);
display_para(2);

The setInterval timers created:

log 0 every 1500 ms
log 1 every 3500 ms
log 2 every 5500 ms

So

timer 0 fires at: 1500   3000   4500  6000  7500 
timer 1 fires at:           3500        7000
timer 2 fires at:                 5500

giving

Expected result:   0     0  1   0 2   0 1   0

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.