Is there a more accurate way to create a Javascript timer than setTimeout?

后端 未结 16 2167
礼貌的吻别
礼貌的吻别 2020-11-22 14:11

Something that has always bugged me is how unpredictable the setTimeout() method in Javascript is.

In my experience, the timer is horribly inaccurate in

16条回答
  •  渐次进展
    2020-11-22 14:41

    You need to "creep up" on the target time. Some trial and error will be necessary but in essence.

    Set a timeout to complete arround 100ms before the required time

    make the timeout handler function like this:

    calculate_remaining_time
    if remaining_time > 20ms // maybe as much as 50
      re-queue the handler for 10ms time
    else
    {
      while( remaining_time > 0 ) calculate_remaining_time;
      do_your_thing();
      re-queue the handler for 100ms before the next required time
    }
    

    But your while loop can still get interrupted by other processes so it's still not perfect.

提交回复
热议问题