0

I have a file (about 10'000 lines) containing the trajectory of my mouse pointer, in the form of a sequence of 2D coordinates and times, like so:

x1,y1,t1
x2,y2,t2
...

The meaning of line k is the following: the pointer was at (xk,yk) at time tk.

The times t1,t2,... are measured in milliseconds. The difference between two consecutive times is not necessarily constant, can be large or go down to below 10 milliseconds.

I want to reproduce this trajectory as an animation in a browser, by having javascript move a small image around, following the above rule. It is important that this be very accurate since it should be synchronized with an audio recording.

I understand that one way of doing is to compute the time differences between the successive positions, and to use setTimeout(). But since the differences can sometimes be under 10 milliseconds, I am afraid that this will lead to some inaccuracies that could pile up as the animation goes. Since the time intervals aren't of constant lenghts setInterval doesn't seem appropriate either.

Is there a better way of doing this? How can one ask javascript to run a certain function at very specific times t1,t2,t3,...,t10000 to ensure the best possible accuracy?

  • See [How to create an accurate timer in javascript?](https://stackoverflow.com/q/29971898/1048572). Instead of adding a fixed `interval` to `expected`, you just get the next timestamp from your list. – Bergi Dec 28 '21 at 16:44
  • Depends. Did you actually *try* the `setTimeout` approach? Or is this just speculative? If it's not just speculative and you really do have issues, you could a) use rAF and poll `Date.now`. Still not guaranteed, but likely higher resolution than just `setTimeout`. Or you could write it in C++ and compile to WASM with emscripten. Again not guaranteed, but higher res. – Jared Smith Dec 28 '21 at 16:44
  • 10ms accuracy is unreasonable. At 60fps, one frame takes slightly more than 16ms. To be able to run at or close to 60fps, use [`requestAnimationFrame()`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) – Ouroborus Dec 28 '21 at 16:52
  • 1
    @Ouroborus OP doesn't actually try to achieve 10ms resolution accuracy, he only needs to prevent accumulating error ("*I am afraid that this will lead to some inaccuracies that could pile up*" - and rightly so). – Bergi Dec 28 '21 at 16:58

0 Answers0