Javascript 计时器不工作(简单但我仍然需要帮助)

标签 javascript html css

我有一个小游戏,我想为它设置一个计时器,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>

最佳答案

你的 RangeError 是由于 minebtc 调用 update 而那个调用 minebtc 一遍又一遍,没有让代码完成运行(因此允许在事件循环中插入其他内容)。要解决此问题,您只需使用 0 毫秒计时器调用 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>

关于Javascript 计时器不工作(简单但我仍然需要帮助),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50438919/

相关文章:

javascript - Joi 覆盖键嵌套模式

javascript - 如何将 mouseposition 设置为元素中心的 0,0 ?

jquery - 尝试使用数据表时出现 mData 错误

jquery - Foundation 粘性菜单链接在 Google Chrome 中不起作用

javascript - 内联 Javascript NOT Rails Heroku 不工作

javascript - 如何将 npm run dev 设置为您的应用程序的启动器?

java - RTF Java 解析器

javascript - 仅限 Safari 浏览器中的右边距

css - 添加属性显示 : table-cell 的 2 <div> 之间的距离

html - 我的 CSS 无法正常工作