I want to add 1 to a number every .5 seconds and display it on a website. This is the code.
<p id="score">
0
</p>
<script></script>
I want to change what is written inside the <p> tag
I want to add 1 to a number every .5 seconds and display it on a website. This is the code.
<p id="score">
0
</p>
<script></script>
I want to change what is written inside the <p> tag
You'll need to access the p element through the Document Object Model API and update the contents of the element within a function that is set to run at .5 second intervals using a timer.
// Get a reference to the paragraph element
const p = document.getElementById("score");
// Set up a recurring timer that takes a function as
// a callback and runs every .5 seconds (500 milliseconds)
// Since the p holds text, putting a + before its contents
// implcitly converts it to a number
setInterval(function(){
p.textContent = +p.textContent + 1;
}, 500);
<p id="score">0</p>
setInterval(function(){
var score = parseInt(document.getElementById("score").innerText);
document.getElementById("score").innerText = score + 1;
}, 500);
<p id="score">
0
</p>
<script>
var score = 0;
var scoreElement = document.getElementById('score');
window.setInterval(function(){
//this function is called every .5 seconds
score ++;
//set text
scoreElement.innerHtml = score;
}, 500)
</script>
Here you go
First, we need to get the p tag in the JS
We can do this in two ways,
const p = document.getElementById('score');
orconst p = document.querySelector('#score');In the second method, we use # since it is an ID. If it were a class, we would use .
Then, to keep track of the score, we need to define a variable, so
score = 0;
Now, we need to make the code run after every .5 seconds, so we need to use the setInterval(); function
so
function() {
our code here
},
our interval here
);
So inside the function, we need to increase the score
so score = score + 1
Now, we need to modify the text, so we will use the innerText method on p, so
p.innerText = score
Now our setInterval() should look like this
setInterval(function() {
score = score + 1;
p.innerText = score;
}
);
Now, we need to define the interval, so after the function ends, we will add 500. This will add the interval of 500ms or .5 seconds.
In the end, our code would be something like this:
const p = document.querySelector('#score');
score = 0;
setInterval(function() {
score = score + 1;
p.innerText = score;
},
500
);
<p id="score"></p>
Full code is here on this Github Gist
https://gist.github.com/AaravHattangadi/ebba0b0c3d088eb471824111db51b594