I have a simple function that takes a target value (3) and generates a random number from 1 to 6 until the target is matched. I want to create a visual effect where I can see each randomly generated number on the page until the target is matched. I assign the randomly generated number to the innerHTML of a p tag each iteration, and can see this happen when I step through the function using browser dev tools. However, when I use setTimeout as shown below and run the function, no delay happens and the target value shows up immediately. Is there a way I can delay each iteration of the while loop so that I can see the randomly generated numbers on screen?
<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(writeOutput(value), 200);
}
}
function writeOutput(value)
{
document.getElementById("output").innerHTML = value;
}
</script>
</body>