1

I have a simple timer to record the time:

let div = document.querySelector('div')
let interval = window.setInterval(function(){
div.textContent =parseFloat(div.textContent)+1
},1)
<div>0</div>

I found that when I switch to another tab, the setInterval will not working.

Are there some simple solution to solve this problem?

I do do some research like, people suggest to use window.requestAnimationFrame, but it doesn't work as well.

Are there some simple solution or built-in function to solve this (I just want to make a simple timer)?

Thanks for any responds!

James
  • 2,732
  • 2
  • 5
  • 28

2 Answers2

1

You could use webworkers, here's a demo

let div = document.querySelector('div')
var blob = new Blob([document.querySelector('#worker').textContent]);
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function() {
    div.textContent =parseFloat(div.textContent)+1
}
<div>0</div>
<script id="worker">
    setInterval(function() { postMessage(''); }, 1);
</script>
35308
  • 575
  • 5
  • 17
  • Appreciate to the answer, but the problem is the setInterval seems not working in the correct way. You set `setInterval` to 1 ms, but it updates much slower than 1 ms. – James Dec 26 '21 at 23:39
1

These days, you should expect that any of your JavaScript can be halted or severely throttled at any time. The reasons for this are usually power-saving initiatives, but can even be security mitigations (in the case of the side-channel attacks in recent years).

If the timer is related to something that is displayed, requestAnimationFrame() is the correct solution. However, you will need to use the system timer to determine the amount of time passed, to decide what to display.

So, if at 1 second your textContent is supposed to equal 'A', and at 2 seconds it is supposed to be 'AB' and so on, you need to assume that the timer might not run at all from 1 second, all the way to say 10 seconds. So at 10 seconds, you determine that the text content is supposed to be 'ABCDEFGHIJ', and display that... even if you never displayed the intermediary values.

Perhaps a better example is in graphics/game development. If a game's frame rate dips from 60 FPS down to 10 FPS, the game movement isn't now 6x slower. It's just that fewer frames are displayed. (This ignores early games of course which were written for specific CPUs and depended on their timing to control the timing in the game.)

Brad
  • 159,648
  • 54
  • 349
  • 530