[英]How to increment a String value by 1 each second JS
I have a value var x = "2"
.我有一个值var x = "2"
。 How can I increment x each second so that one second from when I defined x, x will equal to 3?如何每秒增加 x 以便从定义 x 开始的一秒,x 等于 3?
My code is shown bellow:我的代码如下所示:
<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>
Use a setInterval and set it to one second => 1000
使用 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)
<div id="display">2</div>
You can use javascript setInterval function https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval您可以使用 javascript setInterval function https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
For example:例如:
var x = 0;
setInterval(() => {
x = x + 1;
}, 1000); //1000ms = 1 second
Then each second it will increment the "x" variable.然后每秒它会增加“x”变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.