javascript – How to simulate sluggish browser mangling JS timeout/interval?

Question:

I am writing a timer that ticks once per second, and must do so with an accuracy of 1/200 of a second. Even if the browser is stupid and the computer is weak.

Therefore, I focus not on setTimeout( func, 1000) , but on more frequent calls and system time in milliseconds.

The question is how to test? It is necessary to somehow simulate a different degree of system slowness in order to evaluate the behavior of the script in different conditions. And write to the console deviations in milliseconds from the ideal time of each tick.


Upd. In this algorithm, I run setTimeout () several times within each second for a time less than 1000, and depending on the discrepancy between the actual and expected time of the next launch, and the time remaining until the "end" of the second.

Hypothesis: the brakes of the system do not change significantly in the "window" of one second. Then, by executing several short (200-500ms) preliminary setTimeout() , you can slightly more correctly guess the lag of the next one, and more accurately hit the right time

Upd. 2 found an interesting tip – to test in a virtual machine in which to cut resources.

Answer:

!function() {
  var delta = 100; // Интервал будет плюс-минус 100 милисекунд
  var ost = setTimeout
  setTimeout = function(f, time) {
    time += (Math.random() * 2 - 1) * delta
    ost(f, time)
  }
}()

But generally speaking, your solution is rather strange. More frequent calls will only lead to a greater load on an already slow system, and will not help to measure the intervals more accurately.

The browser is "stupid" for a reason – but because the processor is busy with something else. And if at some point in time the processor is busy, then the script will wake up at the wrong time, regardless of whether the script fell asleep for 20 milliseconds or for 1000.

Scroll to Top