Smooth requestAnimationFrame using Jquery.animate?

I am trying to repeatedly move a div to the right using requestAnimationFrame and Jquery's animate(). However, my div seems to stutter instead of continuously move. How come it keeps starting and stopping?

Here is a JSfiddle of my implementation

If you want to just see my code here is the html:

<body>
  <div id="back">
    <div id="myDiv">
    </div> 
  </div>
</body>

The css:

#myDiv {
  height: 50px;
  width: 50px;
  background-color: black;
  position: absolute;
}

#back {
  height: 200px;
  width: 200px;
  background-color: teal;
}

And the javascript:

  function updateFrame(){
      $("#myDiv").animate({left: '+=25px'}, function(){
        window.requestAnimationFrame(updateFrame);
      });
    }


  updateFrame();

Answers 1

  • Try this:

      function updateFrame(){
          $("#myDiv").animate({left: '+=1px'}, 10, function(){
            window.requestAnimationFrame(updateFrame);
          });
        }
    
    
      updateFrame();
    

    use left: 1px instead of 25px then use animate speed.

    jsFiddle


Related Articles