This counter works fine if it has integers p. 100-150. I want it to count from 70.1 to 88.5. This doesn't work now because it just spins the numbers. What did I do wrong?
let counts=setInterval(updated, 10);
let upto=70.1;
function updated(){
var count= document.getElementById("counter");
count.innerHTML= upto;
if(upto===88.5)
{
clearInterval(counts);
}
}
CodePudding user response:
You had two small but important issues that I fixed. Read the comments I put in the code snippet. This video would help you understand why ===
will never work.
let counts = setInterval(updated, 10);
let upto = 70.1;
function updated() {
var count = document.getElementById("counter");
// upto would never hit 88.5, it will hit 88.1 89.1 -> so we do = 0.1
count.innerHTML = upto = 0.1;
// === would not work properly because of the speed of js so we use >=
if (upto >= 88.5) {
clearInterval(counts);
}
}
<p id="counter"></p>
CodePudding user response:
First: do not increment by 1 ( upto === upto 1). Second: You need to modify your clearInterval condition:
let counts=setInterval(updated, 10);
let upto=70.1;
function updated(){
var count= document.getElementById("counter");
count.innerHTML=upto 0.1;
if(Number(upto.toFixed(1))===88.5)
{
clearInterval(counts);
}
}