I time how long the user has been viewing my webpage. It resets when the user refreshes the webpage.
// This works, increments seconds at the correct speed
setInterval(() => {
let s = document.getElementById("real-s").innerHTML;
document.getElementById("real-s").innerHTML = (Number(s) + 1).toString();
}, 1000)
// This doesn't work, increments seconds too slow (even though 1 s = 1000 ms)
setInterval(() => {
let s = document.getElementById("fake-s").innerHTML;
let ms = document.getElementById("ms").innerHTML;
if (Number(ms) % 1000 === 0 && Number(ms) > 0) {
document.getElementById("fake-s").innerHTML = (Number(s) + 1).toString();
}
document.getElementById("ms").innerHTML = (Number(ms) + 1).toString();
}, 1)
My HTML looks like this:
<p>
You have been on my website for <span id='real-s'>0</span> seconds.
<br/>
You have been on my website for <span id='fake-s'>0</span> fake seconds.
<br/>
You have been on my website for <span id='ms'>0</span> milliseconds.
</p>
I know that a 1000 ms equals 1 s. Based on this, I tried the seconds setInterval() you see above but it doesn’t increment the seconds at the correct speed. Am I doing something wrong or is this just how setInterval() is?
Not sure if this will help you out.
The fake second needs to go pass through an if statement, and will only run when certain conditions are met, so will run slow.
Each setInterval() is running at different rates.
Try setting both setInterval() to 1000 and remove the if condition.
I had the delay of 1000ms deliberately for the setInterval() which increments the fake-seconds because I wanted to see if at every 1000th millisecond it would increment at the expected rate (i.e. at exactly every second).
Is there way to run two callback functions at the exact same time with setinterval()? This way I can get an idea of how much extra time the if statement takes.