本文介绍了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.
推荐答案
<!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>
这篇关于Heads或Tails程序无限循环错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!