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>
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!
Share Improve this question edited Aug 21, 2022 at 2:30 Oleg Barabanov 2,7642 gold badges11 silver badges20 bronze badges asked Aug 21, 2022 at 2:25 CambriaCambria 1532 silver badges14 bronze badges6 Answers
Reset to default 2Put 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>
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>
// 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>
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()
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>
you can also use promise and generator function...
As I told you in my first ment (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>