Click here to Skip to main content
15,881,812 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I am trying to write a simple Heads or tails program, just to practice Javascript.
Here is the code I have so far:
JavaScript
var keys = [];
var choice = Math.random();
window.addEventListener('keydown',function(e){
  keys[e.keyCode] = true;
},false);

window.addEventListener('keyup',function(e){
  delete keys[e.keyCode];
},false);

function main(){
  if (keys[38]){
    flip();
  }
}

function flip(){
  if(choice <0.51){
    document.write('Heads');
    choice = Math.random();
  }else{
    document.write('Tails');
    choice = Math.random();
  }
}

setInterval(function(){
  main();
},1000/30);



It works, and writes either heads or tails to the screen, however it is continuous, and doesn't stop writing to the screen. I wan't it to write the answer once every time you press the up key, rather than it endlessly writing either heads or tails across the screen.
Posted
Comments
Sergey Alexandrovich Kryukov 8-Aug-14 14:05pm    
To start with, what's the scope of this script ("body" element of HTML, "head" element, something else), what function is triggered in first place.
—SA

Try this:
XML
<!DOCTYPE html>
<html>
<body>
<div id="result">Good Luck!</div>

<script>
var placeHolder = document.getElementById('result');

var listener = window.document.addEventListener('keydown', function(e){
       if (e.keyCode == 38) flip();
    }, false);

function flip(){
var choice = Math.random();
   if(choice < 0.51){
      placeHolder.innerText = 'Heads';
   } else {
      placeHolder.innerText = 'Tails';
   }
}

</script>
</body>
</html>
 
Share this answer
 
Not only there are no infinite loops, there are no loops at all in your code. What you see is expected behavior, because your setInterval call explicitly define that main should be called periodically with the period of 1000/30.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900