I'm learning and tried writing a reaction tester. Two questions:
- Why does my while loop continue to run after j exceeds 3? And what can I do against it?
- Is there a better way to achieve what I'm doing here (honestly a bit confused about event driven programming)?
Code:
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style type="text/css">
.buttonBox{
background-color:red;
padding:50px;
border: none;
}
#ersteBox{
position:absolute;
left:500px;
top:300px;
display:none;
}
#zweiteBox{
position:absolute;
left:500px;
top:600px;
display:none;
}
</style>
</head>
<body>
<div>Click the appearing boxes as fast as possible!</div>
<button id="starter">Start</button>
<button id="ersteBox" class="buttonBox"> </button>
<button id="zweiteBox" class="buttonBox"> </button>
<script>
var boxesi=["ersteBox","zweiteBox"];
var j=0;
var i;
document.getElementById("starter").onclick=function(a){
show_random();
while ( j<4 ){
for (let k=0; k<boxesi.length ; k++)
document.getElementById(boxesi[k]).onclick=function(){
if (k==i) {
this.style.display="none";
show_random();
j=j+1;
console.log(j);
};
};
a();
};
alert("done");
};
function show_random(){
i=Math.floor(Math.random()*2);
var b=boxesi[i];
document.getElementById(b).style.display="inline";
};
</script>
</body>
</html>
Edit: Why duplicate? There should be no closure in the loop, since I used let
to define k.
Edit: I applied the changes imposed by Loaf. However, the condition is still not checked.
<script>
var boxesi=["ersteBox","zweiteBox"];
var j=0;
var buttons=[].slice.call(document.getElementsByClassName("buttonBox"));
document.getElementById("starter").onclick=function(a){
show_random();
while ( j<4 ){
buttons.forEach(function(box,k){
box.onclick=function(){
console.log(k);
if (k==i) {
box.style.display="none";
show_random();
j=j+1;
console.log(j);
};
};
});
a();
};
alert("done");
};
function show_random(){
i=Math.floor(Math.random()*2);
var b=boxesi[i];
document.getElementById(b).style.display="inline";
};
</script>