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!
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>
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>