1

I have a value var x = "2". How can I increment x each second so that one second from when I defined x, x will equal to 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>
CoderCookie10
  • 81
  • 1
  • 10

2 Answers2

4

Use a setInterval and set it to one second => 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>
dale landry
  • 7,831
  • 2
  • 16
  • 28
  • 1
    @CoderCookie10 If you look at the wizzywig button bar when editing a question, you'll see the bold **`B`**, italic ***`I`*** buttons and then five buttons directly to the right of those... The fifth button that has a greaterthan/lessthan `<>` symbol will open a code editor. – dale landry May 25 '21 at 04:06
  • Instead of `parseInt`, a lot of people use `x -=- 1` for the same effect... – Jiří Baum May 25 '21 at 05:52
3

You can use 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.