Heads或Tails程序无限循环错误 [英] Heads or Tails program Endless loop error

查看:70
本文介绍了Heads或Tails程序无限循环错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个简单的Heads或tails程序,只是为了练习Javascript。

这是我到目前为止的代码:

I am trying to write a simple Heads or tails program, just to practice Javascript.
Here is the code I have so far:

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.

推荐答案

试试这个:

Try this:
<!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>


不仅没有无限循环,根本没有循环在你的代码中。你看到的是预期的行为,因为你的 setInterval 调用明确定义应定期调用 main ,周期为1000 / 30.



-SA
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


这篇关于Heads或Tails程序无限循环错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆