How to determine the best “framerate” (setInterval delay) to use in a JavaScript animation loop?

后端 未结 5 914
逝去的感伤
逝去的感伤 2020-11-28 10:24

When writing a JavaScript animation, you of course make a loop using setInterval (or repeated setTimeout). But what is the best delay to use in the setInterval/setTimeout ca

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 10:58

    The pseudo-code for this is this one:

    FPS_WANTED = 25 
    (just a number, it can be changed while executing, or it can be constant)
    
    TIME_OF_DRAWING = 1000/FPS_WANTED 
    (this is in milliseconds, I believe it is accurate enough) 
    ( should be updated when FPS_WANTED changes)
    
    UntilTheUserLeavesTheDrawingApplication()
    {
    
      time1 = getTime();
      doAnimation();
      time2 = getTime();
      animationTime = time2-time1;
    
      if (animationTime > TIME_OF_DRAWING)
      {
         [the FPS_WANTED cannot be reached]
         You can:
         1. Decrease the number of FPS to see if a lower framerate can be achieved
         2. Do nothing because you want to get all you can from the CPU
      }
      else
      {
         [the FPS can be reached - you can decide to]
         1. wait(TIME_OF_DRAWING-animationTime) - to keep a constant framerate of FPS_WANTED
         2. increase framerate if you want
         3. Do nothing because you want to get all you can from the CPU
      }
    
    }
    

    Of course there can be variations of this but this is the basic algorithm that is valid in any case of animation.

提交回复
热议问题