我有一个小游戏,我想为它设置一个计时器1秒,但我一直在失败。
计时器使余额随机从0跳到13000 +一些变化。
<script>
var satoshi = 0; var hash = 1;
</script>
<center>
<h4>
Hashs Per Second:
<script type="text/javascript">
document.write(hash)
</script>
</h4>
</center>
<center>
<p id="cookiespersecond">Satoshis: 0</p>
</center>
<button onclick="minebtc()"><img src="kop.png" height=28 width=32>Mine BTC</button>
<button onclick="stop()"><img src="kop.png" height=28 width=32>Stop Mining BTC</button>
<script>
function minebtc() {
satoshi = satoshi + hash
update()
}
function update() {
document.getElementById('cookiespersecond').innerHTML = "Satoshis: " + satoshi;
setTimeout(update, 3000)
minebtc()
}
function stop() {
}
</script>
&#13;
答案 0 :(得分:1)
RangeError
minebtc
呼叫update
并且一次又一次呼叫minebtc
,而不让代码完成运行(因此允许其他内容插入事件循环中)。要解决此问题,您只需使用0ms计时器调用minebtc
,这基本上允许其他事件在您的相互递归之间交错。
<script>
var satoshi = 0; var hash = 1;
</script>
<center>
<h4>
Hashs Per Second:
<script type="text/javascript">
document.write(hash)
</script>
</h4>
</center>
<center>
<p id="cookiespersecond">Satoshis: 0</p>
</center>
<button onclick="minebtc()"><img src="kop.png" height=28 width=32>Mine BTC</button>
<button onclick="stop()"><img src="kop.png" height=28 width=32>Stop Mining BTC</button>
<script>
function minebtc() {
satoshi = satoshi + hash;
setTimeout(update, 3000);
}
function update() {
document.getElementById('cookiespersecond').innerHTML = "Satoshis: " + satoshi;
setTimeout(minebtc, 0)
}
function stop() {
}
</script>
&#13;