1

I am interested in outputting 10 numbers printed one by one using JavaScript.

The HTML code I used to output 10 numbers using JavaScript is:

let z = "";
for (y = 0; y < 11; y = y + 1){
  x = y + 10;
  z = z + " Number " + x + " is printed. <br>";
}

setInterval(function() {
  document.getElementById("demo").innerHTML = z
}, 1000)
<!DOCTYPE html>
<html>

<body>
  <h2>How to use For Loop in JavaScript</h2>
  <p>Output 10 numbers using for loop in Javascript.</p>
  <p id="demo"></p>
</body>

</html>

The problem is that the output is printed all at once after one second instead of printing the output one by one after one second.

How do we modify the code so that the individual output will be printed after one second?

Thank you!

6 Answers 6

2

Put your actual logic inside the interval

let z = "";
let y = 0;

const interval = setInterval(function() {
  if (y >= 11) return clearInterval(interval);
  y++;
  const x = y + 10;
  z = z + " Number " + x + " is printed. <br>";
  document.getElementById("demo").innerHTML = z
}, 1000)
<!DOCTYPE html>
<html>

<body>
  <h2>How to use For Loop in JavaScript</h2>
  <p>Output 10 numbers using for loop in Javascript.</p>
  <p id="demo"></p>
</body>

</html>

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

1 Comment

@WillD fixed𝅷𝅷
1

Use a recursive function with setTimeout instead of setInterval.

function printDelay(max, iteration){
    const newLine = `Number ${iteration + 10} is printed.<br>`;

    const demo = document.getElementById("demo");
    demo.innerHTML = demo.innerHTML + newLine;
    if(iteration < max){
      setTimeout(()=>printDelay(max, iteration + 1),1000);
    }
}

printDelay(10,1);
<!DOCTYPE html>
<html>

<body>
  <h2>How to use For Loop in JavaScript</h2>
  <p>Output 10 numbers using for loop in Javascript.</p>
  <p id="demo"></p>
</body>

</html>

1 Comment

Unique answer!....I've never thought of that one....
1

// init value
var i = 1; 
// func decleartion
function PrintOneByOne() { 
  // setTimeout
  // print for every 3 sec ~ 3000 ms
  // 
  setTimeout(function() {
    z = " Number " + i + " is printed. <br>";
    // append to element
    document.getElementById("demo").innerHTML += z
    i++; 
    if (i <= 10) {
      PrintOneByOne(); 
    } 
  }, 3000)
}

// call func
PrintOneByOne();
<!DOCTYPE html>
<html>

<body>
  <h2>How to use For Loop in JavaScript</h2>
  <p>Output 10 numbers using for loop in Javascript.</p>
  <p id="demo"></p>
</body>

</html>

Comments

1

The problem here is that this part of code is being runned all at once and before the setInterval

let z = "";
for (y = 0; y < 11; y = y + 1){
  x = y + 10;
  z = z + " Number " + x + " is printed. <br>";
}

If you want to print these lines one by one each one second, the best answer is to use setTimeout, like this:

function printNumberEachOneSecond(number) {
    if(number < 11){
        document.getElementById("demo").innerHTML += `Number ${number} is printed. <br>`;
        setTimeout(() => printNumberEachOneSecond(number + 1), 1000)
    }
}
printNumberEachOneSecond(1);

In this case we are using recursion to check if the number is below 11, if it is, we recall the same function after 1000 miliseconds(1 sec).

I don't encorage you to use setInterval because if you do it, you must clear this interval when you don't need it, and doing it may be quite tricky.

Edit: If you reaaally need to use a for loop, use await/async, like this:

async function printNumberEachOneSecond() {
    for(let i = 1 ; i <= 10 ; i++){
        document.getElementById("demo").innerHTML += `Number ${i} is printed. <br>`;
        await new Promise(r => setTimeout(r, 1000))
    }
}
printNumberEachOneSecond()

1 Comment

Good answer. This one's I've never thought of....
1

Everyone answered according their mindset or teaching method. I'm going to tell you a easiest way which can be achieved using two methods

01 - Set interval function, 02 - JS increment...

Now Focus Following

      let totalnum = 10; // loop limit
      let minnum = 0; // starting point
      let printspeed = 0.5 //Print Speed in seconds
      let printer = setInterval(function () { // interval function
        minnum ++; // increment
        if (minnum > totalnum) {
          clearInterval(printer);
        } else {
          // Printing code
          let div = document.createElement('div');
          div.innerHTML = minnum + ' - printed';
          document.getElementById("demo").appendChild(div);
        }
      }, printspeed * 1000);
<p id="demo"></p>
    

1 Comment

Good answer!...another approach....
1

you can also use promise and generator function...

As I told you in my first comment (to which you did not react), you must use a chain of promises.

this can result in JS code like this:

  • there are a lot of technical things to know (the MDN doc is there for that)
    and I'm not some kind of teacher; anyway StackOverflow is not an online college.

start with generator functions

However, if you have any questions... ;)
-- but SO is already full of questions and answers on many technical points used here

const 
  delay   = ms => new Promise(r => setTimeout(r, ms))
, xValues = function* (first,last) { for(i=first;i<=last;i++) yield i }
, pDemo   = document.querySelector('p#demo')
  ;
doMessages()

async function doMessages()
  {
  for await (x of xValues(10,20))
    {
    pDemo.appendChild( document.createTextNode(`Number ${x} is printed`))
    pDemo.appendChild( document.createElement(`br`))
    await delay(1000) 
    }
  }
<h2>How to use For Loop in JavaScript</h2>
<p>Output 11 numbers using for loop in Javascript.</p>
<p id="demo"></p>

3 Comments

promise and generator functions.....I never thought of that one.....
@Cambria You asked to use a for() loop, and I give you two :-)
Very nice...:-)

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.