I am working on a function that generates random numbers between 1 and 6 until it matches a target value of 3. I want to create a visual effect where each randomly generated number is displayed on the page, but I'm facing some challenges with delays. Even though I assign the generated number to a paragraph element during each iteration, when I use setTimeout to introduce a delay, the target value shows up immediately without any delay. Is there a way for me to add a delay between each iteration of the loop so that the generated numbers are displayed on the screen one by one?
<body>
<p id="output"></p>
<button onclick="myFunction()">Go</button>
<script>
function myFunction()
{
var value = 0;
var target = 3;
while (value != target)
{
value = Math.floor((Math.random() * 6) + 1);
setTimeout(function() {
writeOutput(value);
}, 200);
}
}
function writeOutput(value)
{
document.getElementById("output").innerHTML = value;
}
</script>
</body>