I have a html file with a single button on it
<!DOCTYPE html>
<html> <body>
<p>Click the button to list all the items in the array.</p>
<button onclick = "numbers.forEach(myFunction)" >Try it</button>
<p id="demo"></p>
</body>
</html>
I also have the Javascript file containing the onclick function for the .forEach method.
When the button is clicked the I'd like to go through an array, looping through each instance of element in the array.
For every element in this array, I'd like to print out its index and value with a timer afterward that waits a second to display the next permutation.
demoP = document.getElementById("demo");
var numbers = [];
var random = Math.floor(Math.random() * 4) + 1;
numbers.push(random);
function myFunction(item, index) {
random = Math.floor(Math.random() * 4) + 1;
numbers.push(random);
demoP.innerHTML = demoP.innerHTML + "numbers[" + index + "]: " + item + "<br>";
//demoP.innerHTML = demoP.innerHTML + "<br>" //add magic spacing between permutation
sleep(100);
//switch to this and see how slow?
//sleep(1000);
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
What I'd like the result to show when the user clicks the button is:
numbers[0] = 4
//waits a second and adds a <br> here to separate
numbers[0] = 4
numbers[1] = 2
//waits a second and adds a <br> here
numbers[0] = 4
numbers[1] = 2
numbers[2] = 3
and so on.
Currently the code outputs at least twice as many elements, and the sleep() seems to be lasting way longer than it should.
sleepfunction. Instead learn how to do asyc calls through something likesetTimeoutorsetInterval. Also consider usingconsole.logto track your code as it runs. And since you are changing the arraynumberswhile doing aforEachyou are asking for problems. And doing aforEachwithin the DOM elementonclickattribute is not the best way to go. Haveonclickcall a function and do theforEachin that function.