【问题标题】:How to increment a String value by 1 each second JS如何每秒将字符串值增加 1 JS
【发布时间】:2021-08-13 07:36:25
【问题描述】:

我有一个值var x = "2"。如何每秒增加 x 以便从定义 x 开始的一秒,x 等于 3?

我的代码如下所示:

<img src="cookie.jpg" style="text-align:center; width:250px;" id="cookie" onclick="Click()">
<h1 id="score">0</h1>
<script>
  var cookie = document.getElementById("cookie");
  function Click() {
    var scoreStr = document.getElementById("score");
    var score = parseInt(scoreStr.textContent);
    score ++;
    scoreStr.textContent = score;
  }
</script>

【问题讨论】:

  • x 在你的代码中定义在哪里?
  • 根据您的操作,最好存储开始时间,然后在需要时从当前时间中减去它。

标签: javascript html css auto-increment requests-per-second


【解决方案1】:

使用 setInterval 并将其设置为 => 1000

let display = document.getElementById('display')
let x = display.textContent;
// textContent returns a string value

setInterval(()=>{
  // lets change the string value into an integer using parseInt()
  // parseInt would not be needed if the value of x was `typeof` integer already
  display.textContent = parseInt(x++)
}, 1000)
&lt;div id="display"&gt;2&lt;/div&gt;

【讨论】:

  • @CoderCookie10 如果您在编辑问题时查看 wizzywig 按钮栏,您会看到粗体 B,斜体 I 按钮,然后是这些按钮右侧的五个按钮...具有大于/小于 &lt;&gt; 符号的第五个按钮将打开代码编辑器。
  • 很多人用x -=- 1代替parseInt来达到同样的效果...
【解决方案2】:

你可以使用javascript setInterval函数https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

例如:

var x = 0;

setInterval(() => {
  x = x + 1;
}, 1000); //1000ms = 1 second

然后它会每秒递增“x”变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-11-06
    • 2015-09-13
    • 2019-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 1970-01-01
    相关资源
    最近更新 更多