If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

Main content

What DOM animation technique should you use?

You've now seen three techniques that let you animate parts of your webpage: window.setInterval/setTimeout, window.requestAnimationFrame, and CSS animations/transitions.
When you're considering what technique to use, you should consider these questions:
  • Can it actually do what I want to do?
  • How well does this technique perform? (Does it slow down the browser/computer?)
  • How accurate does my timing need to be?
  • Does it work in all the browsers that I want my webpage to work in?
When making webpages, we're very concerned about performance, so we like to consider that as the most important criteria. However, browser performance does change when new browsers come out, and mobile browsers can perform very differently from desktop browsers, so the technique that performs best today may not be the technique that performs best tomorrow. Currently, CSS animations/transitions are the most performant, then requestAnimationFrame, then setInterval.
However, CSS can't do everything. For example, to draw pixels and shapes in a <canvas> tag, you have to call functions like fillRect(), you can't use CSS. You would need to use requestAnimationFrame or setInterval to call those functions periodicially instead. In fact, that's what we do here on Khan Academy, in our ProcessingJS environment. ProcessingJS is a JS library that writes out to a <canvas> tag, and if you define a draw() function in your code, then ProcessingJS uses setInterval to call that draw() function repeatedly based on the frameRate.
Sometimes, you want to call JavaScript functions periodically, but not because you want to animate something on the page. You might be polling a server for updates, like Twitter does when it updates its realtime feed. In that case, you can just use setInterval, and it doesn't matter that the timing isn't accurate, because you're only calling it every minute or so. That's what we do on Khan Academy on the help requests page, to continuously check for new help requests every 2 minutes.
Of course, you should keep browser compatibility in mind. If you're writing code that needs to work in IE9, then you can't use requestAnimationFrame or CSS animations. You need to use a combination of techniques that work across the browsers, or find a library that does that for you, like Velocity.js.
There is a lot more to learn about all of these techniques. Follow these links to learn more:
Bonus for Doctor Who fans: one of my favorite examples of the power of CSS3 animations is this animated TARDIS.

Want to join the conversation?

  • aqualine ultimate style avatar for user Nairit
    When will Khan Academy have more lessons?
    (22 votes)
    Default Khan Academy avatar avatar for user
    • old spice man green style avatar for user Josh (SpongeJr)
      Considering that this course just came out, and it was not long at all before that that the full HTML+CSS course came out, and before that content was added for SQL, and there were new lessons added for a different skill level or devices (using code "blocks" instead of typing). And then the other end of the spectrum was also covered, too, as the "Algorithms" course got added to the CompSci section. And if you go back much further, the JS content that exists now was being expanded-- a couple of times, I think.

      I'd say the answer is to a question like that is: "Pretty darn often, all things considered!" since it seems to me like content gets added regularly. More than once a year seems pretty often to me, and it's been averaging way more than that!

      What sort of lessons were you looking for? Was there something specific you were looking to learn?
      (29 votes)
  • piceratops ultimate style avatar for user trek
    Question @Pamela: some HTML5 here. Is a full unit on HTML5 planned or in progress?
    (2 votes)
    Default Khan Academy avatar avatar for user
  • piceratops ultimate style avatar for user Emily
    (2 votes)
    Default Khan Academy avatar avatar for user
  • female robot ada style avatar for user Opio Paul
    hello guys, i need help,all the challenges above concerning animations have been tricky for me and i have failed to complete any, for the stopwatch challenge i stopped on stage 2 and for the catwalk i failed totally,someone help me
    (1 vote)
    Default Khan Academy avatar avatar for user
  • piceratops ultimate style avatar for user ElsaDragon
    How do I make it so when I click a button, more words show up?
    (2 votes)
    Default Khan Academy avatar avatar for user
  • piceratops sapling style avatar for user Malini Rao
    Hi, I haven't been able to come up with code for Catwalk challenge. I am pretty confused as to how to approach the new left position.
    (2 votes)
    Default Khan Academy avatar avatar for user
    • duskpin ultimate style avatar for user Kimberlina Rodriguez
      This code worked for me:
      <script>
      var catEl = document.getElementById("cat");

      var startTime = new Date().getTime();
      var walkTheCat = function() {
      var currTime = new Date().getTime();
      var secondsElapsed = ((currTime - startTime)/1000);
      var newLeft = secondsElapsed*100;
      catEl.style.left = newLeft + "px";
      window.requestAnimationFrame(walkTheCat);
      };
      walkTheCat();
      </script>
      (3 votes)
  • starky tree style avatar for user vogeleri000
    Can someone show me the code for Challange: Stopwatch. It is so confuziling!
    (1 vote)
    Default Khan Academy avatar avatar for user
    • blobby green style avatar for user adam
      <!DOCTYPE html>
      <html>
      <head>
      <meta charset="utf-8">
      <title>Challenge: Stopwatch</title>
      </head>
      <body>

      <button id="stop-button" type="button">Stop</button>
      <p>
      <span id="seconds">0</span> seconds have gone by!
      </p>
      <script>

      // Make it count up on a timer, calling this function
      var seconds = document.getElementById("seconds");
      var countUp = function() {
      seconds.textContent = parseFloat(seconds.textContent) + 1;
      };

      // How can you make it stop counting?
      var stopCountUp = function() {
      window.clearInterval(t);
      };

      var stopButton = document.getElementById("stop-button");
      stopButton.addEventListener("click", stopCountUp);
      var t = window.setInterval(countUp, 1000);

      </script>
      </body>
      </html>
      (4 votes)
  • hopper cool style avatar for user Electric Dolphin ⚡️🐬
    How do you make it so that if you scroll, an image follows the scrolling?
    (1 vote)
    Default Khan Academy avatar avatar for user
  • male robot hal style avatar for user Jahanzaib Shahid
    I hate web animation what the heck is going on didn't understand anything about animation.
    (1 vote)
    Default Khan Academy avatar avatar for user
    • aqualine ultimate style avatar for user Sam
      To provide an answer for anyone looking for an explanation:

      Animation is the process of showing a bunch of images in sequence to show motion. From a mathematical standpoint, we're essentially defining a function p(t), where t describes the time from the start of the animation, and the output p is the position of the object in question. The trick then is to determine t on each frame.

      setInterval is easy, because the time between frames is constant. Therefore, the input t can be defined as t = t_prev + Δt, where t_prev is the time the previous frame fired at, and Δt is the interval of time between frames. Therefore, you could calculate the time something like this:
      // Call before beginning animation:
      var t = 0;
      ...
      // Call at the start of each frame:
      var t += <insert interval>


      requestAnimationFrame is a bit more complicated, because you have to figure out the amount of time elapsed on the fly. You'd need to somehow reference the current time using a function like Date.now(). Therefore, you need to calculate the time something like this:
      // Call before beginning animation:
      var tStart = Date.now();
      ...
      // Call at the start of each frame:
      var tNow = Date.now() - tStart;

      Where tNow is the number of milliseconds since the animation started.

      Once you determine the time input, you can use that to calculate the position of the object on screen. Due to the fast refresh rate, the object appears to move continuously, and thus animation.
      (2 votes)
  • piceratops ultimate style avatar for user Jade Daniel
    does the browser name "Brave" will work?
    (1 vote)
    Default Khan Academy avatar avatar for user