Why isn't a 1000 ms equal to 1 s with setInterval()?

Hi,

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?

here you are running this interval in every “1ms” is that intended window period for this scope?

happy coding :slight_smile:

You mean am I running the callback function every 1 ms? I am, am I not?

I don’t understand what window period refers to, could you explain that?

Hi there!

window period refers to the browser window, where your website runs.

Sorry, I still don’t understand what you mean. Are you referring to the scope of the callback function?

Hi @haadbhutta

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.

Happy coding

Hi Teller,

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.

here is a thought why not make a “codepen/repl” project with this takeaway and share with us, lets see if we can offer some input on it. happy coding :slight_smile: