Web timer

Is there any way to create a variable speed in the browser that will give the same results for all operating systems and browsers? If I want 140 beats per minute for each user, regardless of their computer speed.

I use javascript setTimeout () and setInterval (), but I think that they depend on the speed of the computer and the amount of code in the program. How to enable system clock in browser? Or any other ideas?

+4
source share
3 answers

You will need to use setTimeout or setInterval in your solution, but this will not be accurate for the following reasons:

  • Browsers have a minimum timeout that is not 0 ms. The minimum browser size is about 14 ms.
  • Timers are inaccurate. They represent the time of the queues, not the runtime. If something else executes when your timer fires, your code enters the wait queue and may not be executed until it appears.

You will probably want to use setTimeout along with manually tracking the current time (using Date ) for your program step. For your case, try something like this:

 function someAction(delta) { // ... } function beat() { var currentTime = +new Date; var delta = currentTime - pastTime; if (delta > 430) { // 430ms ~ 140bpm pastTime = currentTime; someAction(); } setTimeout(beat, 107); // 4x resolution } var pastTime = +new Date; beat(); 

This should be 140 beats per minute, using a higher resolution to avoid large delays. This is just a sample, but you will probably have to work more on it so that it can work optimally for your application.

+6
source

It is best to use setInterval() or try and get something from Date() .

Please note that the time will not be accurate, I think, due to the single-threaded nature of JavaScript.

0
source

The setTimeout() and setInterval() functions are probably the best you get. The timeout parameters for these functions are indicated in milliseconds and do not depend on the overall speed of the computer on which the browser is running.

However, these functions are certainly not hard real-time functions, and if the browser is turned off by taking something else at the time the timeout or interval expires, there may be a slight delay before the callback function is called.

0
source

All Articles