0

I have two loops. How can I run them alternately? For example output of this code:

for (var i = 15; i >= 10; i--) {
  console.log(i)      
}
for (var t = 15; t <= 20; t++) {
  console.log(t)
}

will be:

15 // first loop started
14
13
12
11
10 // first loop ended
15 // second loop started
16
17
18
19
20 // second loop ended

What should i do to get this output:

15 //first loop started
15 //second loop started
14 //first 
16 //second
13 //first
17 //second
12 //first
18 //second
11 //first
19 //second
10 //first loop ended
20 //second loop ended
1

1 Answer 1

3

You could put both initialization, condition and final-expression parts in one for loop.

for (var i = 15, t = 15; i >= 10 && t <= 20; i--, t++) {
    console.log(i)      
    console.log(t)
}

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

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.