Reputation: 3
I would like to instantly print the user input from a prompt in a loop on a div element of id=results . However, the prompt runs 6 times continuously and then all the inputs are printed in the div. I want each input to be printed on div one at a time after each prompt input.
for (let i = 0; i < 7; i++) {
var x = parseInt(prompt("Enter a number"));
h1 = document.createElement('h1');
var result = document.createTextNode('Your inputs are: ' + x);
h1.appendChild(result);
document.getElementById('results').appendChild(h1);
}
<div id="results"></div>
Upvotes: 0
Views: 371
Reputation: 178411
prompt and alert are blocking.
Give the interface time to update the DOM
Try this instead:
let cnt = 7;
const addNum = () => {
let x = parseInt(prompt("Enter a number"));
h1 = document.createElement('h1');
let result = document.createTextNode('Your inputs are: ' + x);
h1.appendChild(result);
document.getElementById('results').appendChild(h1);
cnt--;
if (cnt > 0) setTimeout(addNum,100);
};
addNum();
<div id="results"></div>
Upvotes: 2